PHP Design Pattern Summary _php Tutorial

Source: Internet
Author: User
1. Single Case mode

The so-called Singleton pattern, that is, at any time, only one instance of this class exists in the application. In common, we use singleton mode to allow only one object to access the database, thus preventing multiple database connections from being opened. To implement a singleton class should include the following points:

Unlike ordinary classes, a singleton class cannot be instantiated directly, but only by its own instantiation. Therefore, to achieve such a restrictive effect, the constructor must be marked private.
In order for a singleton class to function without being instantiated directly, you must provide an instance of it. Therefore, the Singleton class must have a private static member variable that can hold an instance of the class and a corresponding public static method that can access the instance.
In PHP, in order to prevent the cloning of a singleton class object to break the above implementation form of the Singleton class, usually also provides an empty private __clone () method for the base.
The following is a basic singleton pattern:
Copy the Code code as follows:
Class Singetonbasic {
private static $instance;

Other VARs.

Private Function __construct () {
DO construct.
}

Private Function __clone () {}

public static function getinstance () {
if (! ( Self:: $instance instanceof Self)) {
Self:: $instance = new self ();
}
Return self:: $instance;
}

Other functions.
}

$a = singetonbasic::getinstance ();
$b = Singetonbasic::getinstance ();
Var_dump ($a = = = $b);

2. Factory mode
The factory pattern is that you can create a class that is designed to implement and return instances of other classes, depending on the input parameters or the configuration of the application. The following is a basic factory model:

Copy the Code code as follows:
Class Factorybasic {
public static function Create ($config) {

}
}

For example, here is a factory that describes Shape objects, and it wants to create different shapes depending on the number of parameters passed in.

Copy the Code code as follows:
Defines the public function of a shape: Gets the perimeter and area.
Interface IShape {
function Getcircum ();
function Getarea ();
}

Defining a Rectangle Class
Class Rectangle implements IShape {
Private $width, $height;

Public function __construct ($width, $height) {
$this->width = $width;
$this->height = $height;
}

Public Function Getcircum () {
Return 2 * ($this->width + $this->height);
}

Public Function Getarea () {
return $this->width * $this->height;
}
}

Defining Circle Classes
Class Circle implements IShape {
Private $radii;

Public function __construct ($radii) {
$this->radii = $radii;
}

Public Function Getcircum () {
Return 2 * M_PI * $this->radii;
}

Public Function Getarea () {
Return M_PI * POW ($this->radii, 2);
}
}

Create different shapes depending on the number of parameters passed in.
Class Factoryshape {
public static function Create () {
Switch (Func_num_args ()) {
Case 1:
return new Circle (Func_get_arg (0));
Break
Case 2:
return new Rectangle (Func_get_arg (0), Func_get_arg (1));
Break

}
}
}

Rectangle Object
$c = Factoryshape::create (4, 2);
Var_dump ($c->getarea ());
Circle Object
$o = Factoryshape::create (2);
Var_dump ($o->getarea ());

Using the Factory mode makes it easier to invoke a method because it has only one class and one method, and if you do not use Factory mode, decide which class and method should be called at the time of invocation, and using Factory mode makes it easier to change the application in the future, such as adding support for a shape, You only need to modify the Create () method in the factory class, instead of using Factory mode, you modify the code block of the calling shape.

3. Observer mode
The Observer pattern gives you another way to avoid tight coupling between components. The pattern is very simple: an object is made observable by adding a method that allows another object, the observer to register itself. When an observable object changes, it sends the message to the registered observer. These observers use this information to perform operations that are independent of observable objects. The result is that objects can talk to each other without knowing why.

A simple example: when the listener is listening to the radio (that is, the station joins a new listener), it sends out a message, which can be observed by the log watcher who sent the message.
Copy the Code code as follows:
Viewer interface
Interface IObserver {
function Onlisten ($sender, $args);
function GetName ();
}

can be observed interface
Interface IObservable {
function Addobserver ($observer);
function Removeobserver ($observer _name);
}

Viewer class
Abstract class Observer implements IObserver {
protected $name;

Public Function GetName () {
return $this->name;
}
}

can be observed class
Class Observable implements IObservable {
Protected $observers = Array ();

Public Function Addobserver ($observer) {
if (! ( $observer instanceof IObserver)) {
Return
}
$this->observers[] = $observer;
}

Public Function Removeobserver ($observer _name) {
foreach ($this->observers as $index = + $observer) {
if ($observer->getname () = = = $observer _name) {
Array_splice ($this->observers, $index, 1);
Return
}
}
}
}

Simulate a class that can be observed: radiostation
Class Radiostation extends Observable {

Public Function AddListener ($listener) {
foreach ($this->observers as $observer) {
$observer->onlisten ($this, $listener);
}
}
}

Simulating an observer class
Class Radiostationlogger extends Observer {
protected $name = ' logger ';

Public Function Onlisten ($sender, $args) {
echo $args, ' join the radiostation.
';
}
}

Simulate another observer class
Class Otherobserver extends Observer {
protected $name = ' other ';
Public Function Onlisten ($sender, $args) {
ECHO ' other observer.
';
}
}

$rs = new Radiostation ();

Inject Observer
$rs->addobserver (New Radiostationlogger ());
$rs->addobserver (New Otherobserver ());

Removing observers
$rs->removeobserver (' other ');

You can see the information you've observed.
$rs->addlistener (' CCTV ');

http://www.bkjia.com/PHPjc/326618.html www.bkjia.com true http://www.bkjia.com/PHPjc/326618.html techarticle 1, Singleton mode so-called Singleton mode, that is, at any time, the application will only have an instance of this class exists. Common, we use the singleton mode to let only one object to visit ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.