php- design patterns

Design mode is essentially a model, if we can understand what the meaning of each mode and effect on the line, the following code example is also in order to facilitate understanding, so try to write clear and concise

Example 1. Single Mode 

  Description: there is only one kind of global an example, and not create a copy, can not be instantiated because it is necessary to provide the inlet (static method a) obtaining a example of the external

  Action: (1) in a single run, will not be instantiated multiple times can reduce memory overhead.

     (2) in the database, for example, can also be eliminated only once instantiated links, disconnection repeat

     (3) Because only one instance, the configuration information may be controlled globally

  achieve:

<?php
class Single
{
    static private $instance;                            //实例
    private $conf;                                       //配置
    public $param;
    private function __construct($conf)                  //防止new
    {
        $this->conf = $conf;
    }
    private function __clone() {}                        //防止clone
    private function __sleep() {}                        //防止序列化
    
    static public function getInstance($conf)
    {
        if (! self::$instance)
        {
            self::$instance = new self($conf);
        }
        return self::$instance;
    }
}

//测试
$s1 = Single::getInstance(array());
$s2 = Single::getInstance(array());

$s1->param = 's1';
echo $s1->param;                                            //s1
echo $s2->param;                                            //s1

$s2->param = 's2';
echo $s1->param;                                            //s2
echo $s2->param;                                            //s2

?>

 

2. Factory Pattern

  Description: When a need example does not require new, top parameters directly from the plant belonging to the retrieval mode on the line

  Action: (1) easy to manage, easy to expand

     (2) the name and location of the external file does not need to be concerned about the class, simply pass the corresponding number on the line

  achieve:

<?php

class class1{};
class class2{};
class class3{};

class Factory
{
    private static $classes = [                         //可返回类
        1 => 'class1',
        2 => 'class2',
        3 => 'class3',
    ];
    static public function create($num)
    {
        if (isset(self::$classes[$num]))
        {
            return new self::$classes[$num]();
        }
        return false;
    }
}

$class = Factory::create(1);

?>

3. Observer pattern

  Description: Multiple observers observed a theme object when the object is the theme of change (here only refers to a trigger condition), so that the observer will notify the observer (in fact, polling to perform a function of the observer)

  Role: Looks may still vague, but look at the code will be able to understand, and very simple in nature. For example, if I was a theme objects, I entered a trigger condition, the lamp will open (light is an observer), will open the TV (television viewers), and so on. . Here is a look at how many viewers you registered

In the project, we will also have a series of actions after the user registration (such as Fat Station Letters, send new coupon or something), these actions can be registered as an observer, observed only after the user has registered automatically on the line

  achieve:

? < PHP 

// here which method limits class must implement the interface, in order to look more concise whole that is not a useless 
class the Action 
{ 
    Private  $ Observers = []; 
    
    // register an observer 
    public  function the attach ( $ observer ) 
    { 
        $ the this -> observers [] = $ observer ; 
    } 
    
    // log off a viewer 
    public  function the detach ( $ observer ) 
    { 
        $ K = the array_search ( $ observer , $ the this -> observers);
         IF ( $ K) unset ($this->observers[$k]);
    }
    
    //通知
    public function notify()
    {
        foreach ($this->observers as $observer)
        {
            $observer->update();
        }
    }
}

//观察者们
class Observer1
{
    function update(){echo 'Observer1';}
}
class Observer2
{
    function update(){echo 'Observer2';}
}

$action = new Action();
$action->attach(new Observer1());
$action->attach(new Observer2());
$action->notify();
?>

  Supplementary (personal opinion): I think the name is not very accurate observer, because the observer from the implementation point of view is not active trigger, but the action will have to be notified. They also did not observe the implementation of this action. If you really want to complete this action observation I can think it can only have been a while, while conditions may be a pointer to a theme feature value of an object, observe the theme has not changed. But such spending big.

 

4. Adapter Mode

  Description: can be used as a middleware on the previous secondary treatment at the object and then form a new interface,

  Role: In order to meet the new requirements, derived from the old interface to the new interface, in order to save a lot of duplicate code reuse and flexibility of the new interfaces will use the old interface code, and do secondary treatment. If we used to have three interfaces, namely, fried rice, fried noodles, fried. Recently found that users like to eat beef, we added three new beef fried rice, beef noodles, beef fried. If all the old interfaces have changed what the cost is relatively big, and if you still have the customer point of fried rice, fried noodles we have to consider compatibility. So if a user point beef fried rice we produce interfaces old tune like a fried rice and (relatively speaking about, in fact, the principle is very simple look at the code to understand) is added thereto in the beef

  achieve:

<?php
class Rice
{
    public function dosomething()
    {
        return 'fry rice';                                                      // 炒饭
    }
}

class Noodles
{
    public function dosomething()
    {
        return 'fry noodles';                                                   //炒面
    }
}

class Adapter                                                                  //适配器
{
    private $obj;
    public function __construct($obj) 
    {
        $this->obj = $obj;
    }
    public function dosomething()
    {
        $res = $this->obj->dosomething();
        return $res . ' add fat cattle';                                        //加肥牛
    }
}
    
$adapter1 = new Adapter(new Rice());
$adapter2 = new Adapter(new Noodles());
echo $adapter1->dosomething();                                                  //fry rice add fat cattle  
echo $adapter2->dosomething();                                                  //fry noodles add fat cattle
?>

 

5. Strategy mode (this did not get to know his meaning)

  Note: You can select the functions they need in the current environment, we need which method to use, which directly target the new. Those objects can also be handed over to the factory management mode

  Action: is to prevent the use of complex and cumbersome if ... else or switch ... case brought below. I had never get to know that ye do not if..else, and always felt like the pants off fart (my understanding is not deep, but maybe a year or two I realized he was good, and that time I deleted here), look at the code it

  achieve:

<? PHP
 // briefly explain in this example I want to achieve two numbers together, here I'll just write method, and convenient. 
// first is the traditional method of 
$ num1 =. 1 ;
 $ num2 = 2 ;
 function CAL ( $ num1 , $ num2 , $ Oper ) 
{ 
    // $ Oper symbol, according to the sign determining what the user wants, there is not much better if Well ..else 
    IF ( $ Oper == '+' ) 
    { 
        return  $ num1 + $ num2 ; 
    } 
    the else  IF ( $ Oper == '-' ) 
    { 
        return  $ num1 - $ num2 ;
    }
    the else 
        return  to false ; 
} 

// I want to add two numbers, so I pass plus 
echo CAL ( $ num1 , $ num2 , '+' );       

// ----------------------- -------------------------------------------Dividing line----- -------------------------------------------------- 

// now strategies mode 
function the Add ( $ num1 , $ num2 ) 
{ 
    return  $ num1 + $ num2 ; 
} 

function context ( $ num1 , $ num2 , $ Fun ) 
{ 
    return  $ Fun ( $ num1 , $ num2 ); 
} 
echo context ( $ num1 , $ num2 , add);                             // here I pass directly add this function downstream will not have to determine the direct execution on the line 

// added: check the internet a lot (both another set, or pull a number of sets of words, write a demo so long looked too old strenuous), may be understood or wrong, this object is achieved with such a meaning is probably still feel fart in your pants off 
?>

 

6. Decorator

  Description: a type of function to be modified or added

  Role: In order to cope with more scenes, the need for functional classes were added and modified, in fact, we have inherited way can also be used, but if a lot of class (inherited from the same interface) to be unified to add and modify a feature, not a you write a lot of sub-categories and with the increase of extensions, subclasses will be expanded

  achieve:

? < PHP
 // C1 C2 are two classes decorated 
class a C1 
{ 
    function GET () 
    { 
        return 100 ; 
    } 
} 

class C2 
{ 
    function GET () 
    { 
        return 200 is ; 
    } 
} 

// This is the decorator 
class the Decorator 
{ 
    Private  obj $ ;
     public  function the __construct ( $ obj ) 
    { 
        $ the this -> obj = $ obj ; 
    } 
    function  GET ()
    {
        $res = $this->obj->get();
        return $res / 10;
    }
    
    function newGet()
    {
        $res = $this->obj->get();
        return $res + 1;
    }
}
//测试
$obj1 = new Decorator(new C1());
$obj2 = new Decorator(new C2());
echo $obj1->get();
echo $obj1->newGet();
echo $obj2->get();
echo $obj2->newGet();

?>

  Added: looks like two different points (1) adapter to adapt to the new environment and adapter not like, personal summary of the parameters and invocation are likely to change, for example, I add a type parameter, the adapter to do an expansion for this. But decorator will not call the same manner and to ensure that before, just to function on the basis of prior 'decorative' more beautiful. (2) definition, including modifications not only decorative, but also includes new

Guess you like

Origin www.cnblogs.com/wangjianheng/p/11512643.html