PHP design mode

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:

    classSingetonbasic {Private Static $instance; //Other VARs .    Private function__construct () {//Do construct.    }    Private function__clone () {} Public Static functiongetinstance () {if(! (Self::$instanceinstanceof Self)) { Self::$instance=NewSelf (); }        returnSelf::$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:

    class Factorybasic {    publicstaticfunction 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. InterfaceIShape {functionGetcircum (); functionGetarea ();}//Defining a Rectangle classclassRectangleImplementsIShape {Private $width,$height;  Public function__construct ($width,$height) {        $this->width =$width; $this->height =$height; }     Public functionGetcircum () {return2 * ($this->width +$this-height); }     Public functionGetarea () {return $this->width *$this-height; }}//Defining Circle ClassesclassCircleImplementsIShape {Private $radii;  Public function__construct ($radii) {        $this->radii =$radii; }     Public functionGetcircum () {return2 * M_PI *$this-radii; }     Public functionGetarea () {returnM_PI *POW($this->radii, 2); }}//create different shapes depending on the number of parameters passed in. classFactoryshape { Public Static functionCreate () {Switch(Func_num_args()) {             Case1:return NewCircle (Func_get_arg(0));  Break;  Case2:return NewRectangle (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 pattern

    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 InterfaceInterfaceIObserver {functionOnlisten ($sender,$args); functiongetName ();}//can be observed interfaceInterfaceiobservable {functionAddobserver ($observer); functionRemoveobserver ($observer _name);}//Viewer ClassAbstract classObserverImplementsIObserver {protected $name;  Public functionGetName () {return $this-name; }}//can be observed classclassObservableImplementsiobservable {protected $observers=Array();  Public functionAddobserver ($observer) {        if(! ($observerinstanceof IObserver)) {            return; }        $this->observers[] =$observer; }     Public functionRemoveobserver ($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: radiostationclassRadiostationextendsObservable { Public functionAddListener ($listener) {        foreach($this->observers as $observer) {            $observer->onlisten ($this,$listener); }    }}//simulating an observer classclassRadiostationloggerextendsObserver {protected $name= ' Logger ';  Public functionOnlisten ($sender,$args) {        Echo $args, ' Join the radiostation.<br/> '; }}//simulate another observer classclassOtherobserverextendsObserver {protected $name= ' other ';  Public functionOnlisten ($sender,$args) {        Echo' Other observer. <br/> '; }}$rs=Newradiostation ();//Inject Observer$rs->addobserver (NewRadiostationlogger ());$rs->addobserver (Newotherobserver ());//removing observers$rs->removeobserver (' other '));//you can see the information you've observed.$rs->addlistener (' CCTV ');

PHP design mode

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.