Php design mode, design mode _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Php design mode. Php design mode: 1. factory mode: Factory mode is a type, which has some methods to create objects for you. You can use the factory class to create objects, php design mode, design mode

Several modes:

1. factory model

Factory mode is a type that provides methods for creating objects for you.

You can use the factory class to create objects instead of using new directly. In this way, if you want to change the type of the created object, you only need to change the factory. All codes used in the factory are automatically changed.

Functions and classes in a certain 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 modes to enable these classes to communicate with each other, but do not want to closely bind them together to avoid interlocking.

In large systems, many codes depend on a few key classes. It may be difficult to change these classes.

2. single element mode

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

For example, the connection from a database handle to a database is exclusive.

You want to share the database handle in the application, because it is an overhead when you keep the connection open or closed, especially when you get a single page.

3. Observer Mode

The Observer Mode provides another way to avoid close coupling between components.

This mode is very simple: an object becomes observability by adding a method (this method allows another object, that is, the Observer registers itself.

When an observed object changes, the message is sent to the registered observer. The operations performed by these observers using this information are irrelevant to the observed objects. The result is that objects can communicate with each other without understanding the cause.

4. command chain mode

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

Each handler determines whether it can process the request. If yes, the request is processed and the process stops. You can add or remove a handler for the system without affecting other handlers.

5. policy mode

The last design pattern we talk about is the strategy pattern. In this mode, algorithms are extracted from complex classes and can be easily replaced.

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

Think about the several parts of the search engine-one part traverses the page, the other part sorts each page, and the other part sorts the results based on the arrangement.

In a complex example, these parts are in the same class. By using the policy mode, you can place the arranged parts into another class to change the page arrangement method without affecting the rest of the search engine code.

Common modes:

1. Singleton mode (three private and one public)

①. Private constructor (access control: prevents external code from using the new operator to create objects. a singleton class cannot be instantiated in other classes but can only be instantiated by itself)

② Private static attributes (static member variables of an instance with a storage class)

③ Private cloning method (a public static method for accessing the instance, and the getInstance () method is often used to instantiate the singleton class, the instanceof operator can be used to check whether the class has been instantiated)

④ Public static methods (preventing objects from being copied)

The Singleton mode means that only one instance of this class exists in the application at any time.

Generally, we use the Singleton mode to allow only one object to access the database, thus preventing multiple database connections from being opened.

To implement a singleton class, you must include the following:

Unlike normal classes, a singleton class cannot be directly instantiated, but can only be instantiated by itself. Therefore, to obtain such a restricted effect, the constructor must be marked as private.

To make a singleton class effective without being directly instantiated, you must provide such an instance for it.

Therefore, the singleton class must have a private static member variable that can save the class and a public static method that can access the instance.

In PHP, to prevent the singleton class object from being cloned to break the preceding implementation form of Singleton classes, an empty private _ clone () method is also provided for the basics.

Below is a basic Singleton mode:

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 model

The factory mode allows you to create a class dedicated to implementation and return other classes based on input parameters or application configurations. Below is a basic factory model:

Class FactoryBasic {

Public static function create ($ config ){

}

}

For example, this is a factory that describes shape objects. it wants to create different shapes based on the number of input parameters.

// Define the common function of the shape: obtain the length and area of the week.

Interface IShape {

Function getCircum ();

Function getArea ();

}

// Define the 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;

}

}

// Define the circle class

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 based on the number of input parameters.

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;

}

}

}

// Rectangular 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 call a method because it only has one class and one method. if the factory mode is not used, it is necessary to decide which class and method should be called during the call;

Using the factory mode also makes it easier to change the application in the future. for example, to add a shape support, you only need to modify the create () method in the factory class, if the factory mode is not used, modify the code block of the called shape.

3. Observer Mode

The Observer Mode provides another way to avoid close coupling between components.

This mode is very simple: an object becomes observability by adding a method (this method allows another object, that is, the Observer registers itself.

When an observed object changes, the message is sent to the registered observer. The operations performed by these observers using this information are irrelevant to the observed objects. The result is that objects can communicate with each other without understanding the cause.

A simple example: when a listener is listening to a station (that is, a new listener is added to the station), it sends a prompt message, which can be observed by the log observer who sends the message.

// Observer interface

Interface IObserver {

Function onListen ($ sender, $ args );

Function getName ();

}

// Interface to be observed

Interface IObservable {

Function addObserver ($ observer );

Function removeObserver ($ observer_name );

}

// Observer class

Abstract class Observer implements IObserver {

Protected $ name;

Public function getName (){

Return $ this-> name;

}

}

// Class to be observed

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 );

}

}

}

// Simulate 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 the Observer

$ Rs-> addObserver (new RadioStationLogger ());

$ Rs-> addObserver (new OtherObserver ());

// Remove the Observer

$ Rs-> removeObserver ('other ');

// You can see the observed information.

$ Rs-> addListener ('CCTV ');

Http://www.bkjia.com/PHPjc/989816.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/989816.htmlTechArticlephp design patterns, design patterns several patterns brief: 1. factory patterns are a type that has some ways to create objects for you. You can use the factory class to create an object ,...

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.