Some summaries of design patterns on the PHP network

Source: Internet
Author: User
Tags zend framework
1. Single-case mode

The singleton pattern, as its name implies, is only one instance. As an object's creation mode, Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole.

The main points of the singleton pattern are three:

One is that a class can have only one instance;

The second is that it must create this instance on its own;

Thirdly, it must provide this instance to the whole system on its own.

Why use PHP singleton mode

1. The application of PHP is mainly in the database application, there will be a large number of database operations in an application, when the use of object-oriented development, if the use of Singleton mode, you can avoid a large number of new operations consumed by the resources, but also reduce the database connection so it is not easy to appear too many Connections situation.

2. If a class is needed in the system to control some configuration information globally, it can be easily implemented using singleton mode. This can be see the Frontcontroller section of the Zend Framework.

3. In a page request, it is easy to debug, because all the code (such as database Operation class DB) is concentrated in a class, we can set the hooks in the class, output the log, so as to avoid var_dump everywhere, echo.


Example:

/** * Design mode singleton mode * $_instance must be declared as a static private variable * The constructor must be declared private, preventing the external program new class from losing the meaning of the singleton pattern * The getinstance () method must be set to public, This method must be called to return a reference to an instance of *:: Operators can only access static variables and static functions * new objects consume memory * Usage scenarios: The most common place is the database connection. * Once an object is generated using singleton mode, the object can be used by many other objects.    */class man{//Save example Instance private static $_instance in this attribute; The constructor is declared private, preventing direct creation of the object Private function __construct () {echo ' I was instantiated!    ';                }//Singleton method public static function Get_instance () {Var_dump (Isset (self::$_instance));        if (!isset (self::$_instance)) {self::$_instance=new self ();    } return self::$_instance;    }//prevents the user from copying the object instance private function __clone () {Trigger_error (' clone is not allow ', e_user_error);    } function Test () {echo ("test"); }}//This notation is error, because the constructor method is declared as private//$test = new man;//The following will get the example class of the Singleton object $test = Man::get_instance (); $test = man::get_ Instance (); $test->test ();//Copying an object will result in a e_user_error.//$test _clone = Clone $test;

2. Simple Factory mode

① abstract base class: Some methods of defining abstractions in classes to implement in subclasses

② inherits from the subclass of the abstract base class: Implementing an abstract method in a base class

③ Factory class: Used to instantiate all the corresponding sub-classes

/** * * Defines an abstract class that allows subclasses to inherit to implement it */abstract class operation{//Abstract method cannot contain function body abstract publi C function GetValue ($num 1, $num 2);//strongly require subclasses to implement the function function}/** * Addition class */class Operationadd         Extends operation {public Function getValue ($num 1, $num 2) {return $num 1+ $num 2; }}/** * Subtraction class */class Operationsub extends Operation {public Function getValue ($num 1, $num 2         ) {return $num 1-$num 2; }}/** * Multiplication class */class Operationmul extends Operation {public Function getValue ($num 1, $num 2         ) {return $num 1* $num 2; }}/** * Division class */class Operationdiv extends Operation {public Function getValue ($num 1, $num 2                 {try {if ($num 2==0) {throw new Exception ("divisor cannot be 0");                 }else {return $num 1/$num 2;             }}catch (Exception $e) {echo "error message:". $e->getmessage (); }         }     }

By using object-oriented inheritance, we can easily extend the original program, such as: ' exponentiation ', ' root ', ' log ', ' trigonometric ', ' statistics ' and so on, so that you can also avoid loading unnecessary code.


If we need to add a redundancy class now, it will be very simple.

We only need to write another class (the class inherits the virtual base class), in the class to complete the corresponding functions (such as: exponentiation), and greatly reduce the coupling degree, convenient for future maintenance and expansion

/**     * (remainder) * * *     /    class Operationrem extends operation {public        function GetValue ($num 1,$ NUM2) {            return $num 1% $num;        }    }

Now there is one more question unresolved, that is, how can the program instantiate the corresponding object according to the user input operator?
Workaround: Use a separate class to implement the instantiation process, which is the factory

  /**     * Engineering class, mainly used to create objects     * Function: According to the input operation symbol, the factory can instantiate the appropriate object     * */    class factory{public        static function Createobj ($operate) {            switch ($operate) {case                ' + ':                    return new Operationadd ();                    break;                Case '-':                    return new Operationsub ();                    break;                Case ' * ':                    return new Operationsub ();                    break;                Case '/':                    return new Operationdiv ();                    Break    ;    }}} $test =factory::createobj ('/');    $result = $test->getvalue (23,0);    echo $result;

Other notes on this pattern:

Factory mode:
Take the transportation as an example: request to be able to customize the transportation, but also can customize the transportation production process
1> Custom Transportation
1. Define an interface containing the method of the completion tool (Start Operation stop)

2. Let aircraft, cars and other classes to achieve their
2> Custom-made factory (on-site similar)
1. Define an interface containing the manufacturing method of the completion tool (start-up operation stop)

2. Write the manufacturing aircraft, the car factory class to inherit the implementation of this interface

3. Observer mode


The Observer pattern is a behavior pattern, which defines a one-to-many dependency between objects, so that when an object's state changes, all objects that depend on it are notified and refreshed automatically. It perfectly separates the observer object from the object being observed. You can maintain a list of dependencies (observers) that are of interest to the principal in a stand-alone object (body). Let all observers implement a common Observer interface to remove the direct dependencies between the principal and the dependent objects. (I can't understand it anyway)


Use of SPL (Standard PHP library)

Class MyObserver1 implements Splobserver {public Function update (Splsubject $subject) {echo __class__. ' - ' .    $subject->getname (); }}class MyObserver2 implements Splobserver {public Function update (Splsubject $subject) {echo __class__. ' - ' .    $subject->getname ();    }}class Mysubject implements Splsubject {private $_observers;    Private $_name;        Public function __construct ($name) {$this->_observers = new Splobjectstorage ();    $this->_name = $name;    The Public function attach (Splobserver $observer) {$this->_observers->attach ($observer);    The Public function detach (Splobserver $observer) {$this->_observers->detach ($observer); The Public Function notify () {foreach ($this->_observers as $observer) {$observer->update ($this        );    }} Public Function GetName () {return $this->_name; }} $observer 1 = new MyObserver1 (), $observer 2 = new MyObserver2 ();$subject = new Mysubject ("test"), $subject->attach ($observer 1), $subject->attach ($observer 2); 

$subject->notify ();

4. Policy mode

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.

As a simpler example, the following shows a user list class that provides a way to find a group of users based on a set of Plug and Play policies

Define interface interface IStrategy {function filter ($record);}    Implement Interface mode 1class Findafterstrategy implements IStrategy {private $_name;    Public function __construct ($name) {$this->_name = $name;    The Public Function filter ($record) {return strcmp ($this->_name, $record) <= 0; }}//Implement Interface Mode 1class Randomstrategy implements IStrategy {public Function filter ($record) {return rand (0, 1) &G    T;= 0.5;    }}//Master Class class UserList {private $_list = array ();                Public function __construct ($names) {if ($names! = null) {foreach ($names as $name) {            $this->_list [] = $name;    }}} Public function Add ($name) {$this->_list [] = $name;        The Public function find ($filter) {$recs = array ();        foreach ($this->_list as $user) {if ($filter->filter ($user)) $recs [] = $user;    } return $recs; }} $ul = new UserList (ARRAY ("Andy", "Jack", "Lori", "Megan")), $f 1 = $ul->find (new Findafterstrategy ("J"));p Rint_r ($f 1); $f 2 = $ul->find (new Randomstrategy ());

Print_r ($f 2);

The strategy model is ideal for complex data management systems, or for data processing systems, which require greater flexibility in the way they are filtered, searched, or processed

  • 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.