PHP Design Patterns, Design patterns _php Tutorials

Source: Internet
Author: User

PHP Design patterns, Design patterns


A brief description of several modes:

1. Factory mode

A factory pattern is a class that has some methods for creating objects for you.

You can use the factory class to create objects without using new directly. This way, if you want to change the type of object you are creating, you can simply change the factory. All code that uses the factory is automatically changed.

Functions and classes in a part of the system depend heavily on the behavior and structure of functions and classes in other parts of the system.

You need a set of patterns that enable these classes to communicate with each other, but do not want to tightly bind them together to avoid interlocking.

In large systems, many of the code relies on a few key classes. There may be difficulties when you need to change these classes.

2. Single element mode

Some application resources are exclusive because there is only one resource of this type.

For example, a connection to a database through a database handle is exclusive.

You want to share a database handle in your application because it is a cost when keeping a connection open or closed, especially if you are getting a single page.

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.

4. Command chain mode

The command chain pattern is based on loosely coupled topics, sending messages, commands, and requests, or sending arbitrary content through a set of handlers.

Each handler will decide for itself whether it can handle the request. If it can, the request is processed and the process stops. You can add or remove handlers for the system without affecting other handlers.

5. Strategy mode

The last design pattern we've talked about is the strategy model. In this mode, the algorithm is extracted from the complex class and can therefore be easily replaced.

For example, if you want to change the way a page is arranged in a search engine, the policy mode is a good choice.

Think about several parts of the search engine--part of the traversal page, one for each page, and one for the sorted results.

In a complex example, these parts are in the same class. By using the policy mode, you can put the arrangement part in another class to change the way the page is arranged without affecting the rest of the search engine's code.

General patterns:

1, single case mode (three private one public)

①, Private construction method (Access control: Prevents external code from creating objects using the new operator, singleton classes cannot be instantiated in other classes, they can only be instantiated by themselves)

②, private static property (owns a static member variable that holds an instance of the class)

③, private cloning method (with a common static method to access this instance, common getinstance () method to instantiate a singleton class, through the instanceof operator can detect whether the class has been instantiated)

④, public static methods (prevents objects from being copied)

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:

Class Singetonbasic {

private static $instance;

Private Function __construct () {

DO construct.

}

Private Function __clone () {}

public static function getinstance () {

if (! ( Self:: $instance instanceof Self)) {

Self:: $instance = new self ();

}

Return self:: $instance;

}

}

$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:

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.

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;

Using the Factory mode also makes it easier to change the application in the future, such as adding support for a shape, modifying the Create () method in the factory class instead of using Factory mode, and modifying 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.

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/989816.html www.bkjia.com true http://www.bkjia.com/PHPjc/989816.html techarticle php Design Patterns, design patterns of several modes briefly: 1, Factory mode Factory mode is a class that has some methods for creating objects for you. You can use the factory class to create objects, ...

  • Related Article

    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.