Home  >  Article  >  类库下载  >  Some summaries about design patterns on the PHP Internet

Some summaries about design patterns on the PHP Internet

高洛峰
高洛峰Original
2016-10-14 10:25:181043browse

1. Singleton mode

Singleton mode, as the name suggests, means that there is only one instance. As an object creation mode, the singleton mode ensures that a class has only one instance, instantiates itself and provides this instance to the entire system.

There are three main points of the singleton pattern:

First, a class can only have one instance;

Second, it must create this instance by itself;

Third, it must provide this instance to the entire system by itself.

Why use PHP singleton mode

1. PHP is mainly used in database applications. There will be a large number of database operations in an application. When developing in an object-oriented way, if you use the singleton mode, you can avoid a large number of operations. The new operation consumes resources and can also reduce database connections so that too many connections are less likely to occur.

2. If a class is needed to globally control certain configuration information in the system, it can be easily implemented using the singleton mode. This can be found in the FrontController part of 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 one class. We can set hooks in the class and output logs to avoid var_dump and echo everywhere.


Example:

/**
 * 设计模式之单例模式
 * $_instance必须声明为静态的私有变量
 * 构造函数必须声明为私有,防止外部程序new类从而失去单例模式的意义
 * getInstance()方法必须设置为公有的,必须调用此方法以返回实例的一个引用
 * ::操作符只能访问静态变量和静态函数
 * new对象都会消耗内存
 * 使用场景:最常用的地方是数据库连接。
 * 使用单例模式生成一个对象后,该对象可以被其它众多对象所使用。
 */
class man
{
    //保存例实例在此属性中
    private static $_instance;

    //构造函数声明为private,防止直接创建对象
    private function __construct()
    {
        echo '我被实例化了!';
    }

    //单例方法
    public static function get_instance()
    {
        var_dump(isset(self::$_instance));
        
        if(!isset(self::$_instance))
        {
            self::$_instance=new self();
        }
        return self::$_instance;
    }

    //阻止用户复制对象实例
    private function __clone()
    {
        trigger_error('Clone is not allow' ,E_USER_ERROR);
    }

    function test()
    {
        echo("test");

    }
}

// 这个写法会出错,因为构造方法被声明为private
//$test = new man;

// 下面将得到Example类的单例对象
$test = man::get_instance();
$test = man::get_instance();
$test->test();

// 复制对象将导致一个E_USER_ERROR.
//$test_clone = clone $test;

2. Simple factory pattern

①Abstract base class: Define some abstract methods in the class to implement them in subclasses

②Subclasses that inherit from abstract base classes: Implement abstract methods in the base class

③Factory class: used to instantiate all corresponding subclasses

Some summaries about design patterns on the PHP Internet

 /**
     * 
     * 定义个抽象的类,让子类去继承实现它
     *
     */
     abstract class Operation{
         //抽象方法不能包含函数体
         abstract public function getValue($num1,$num2);//强烈要求子类必须实现该功能函数
     }
     
     
     
     /**
      * 加法类
      */
     class OperationAdd extends Operation {
         public function getValue($num1,$num2){
             return $num1+$num2;
         }
     }
     /**
      * 减法类
      */
     class OperationSub extends Operation {
         public function getValue($num1,$num2){
             return $num1-$num2;
         }
     }
     /**
      * 乘法类
      */
     class OperationMul extends Operation {
         public function getValue($num1,$num2){
             return $num1*$num2;
         }
     }
     /**
      * 除法类
      */
     class OperationDiv extends Operation {
         public function getValue($num1,$num2){
             try {
                 if ($num2==0){
                     throw new Exception("除数不能为0");
                 }else {
                     return $num1/$num2;
                 }
             }catch (Exception $e){
                 echo "错误信息:".$e->getMessage();
             }
         }
     }

By using object-oriented inheritance features, we can easily extend the original program, For example: 'power', 'square root', 'logarithm', 'trigonometric function', 'statistics', etc., to avoid loading unnecessary code.


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

We only need to write another class (this class inherits the virtual base class) and complete the corresponding functions in the class (for example: multiplication square operation), and greatly reduces the coupling degree, which facilitates future maintenance and expansion

 /**
     * 求余类(remainder)
     *
     */
    class OperationRem extends Operation {
        public function getValue($num1,$num2){
            return $num1%$num12;
        }
    }

There is still an unresolved problem, which is how to let the program instantiate the corresponding object according to the operator input by the user?
Solution: Use a separate class to implement the instantiation process, this class is the factory]

/**
     * 工程类,主要用来创建对象
     * 功能:根据输入的运算符号,工厂就能实例化出合适的对象
     *
     */
    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 about this pattern:

Factory pattern:
Take transportation as an example: please ask for it Customized transportation means you can also customize the process of transportation production
1> Customize transportation
1. Define an interface that contains the methods of delivering the tool (start, run, stop)

2. Let airplanes, cars, etc. implement them
2> Customized factory (similar to above)
1. Define an interface, which contains the manufacturing method of delivery tools (start, run, stop)

2. Write factory classes for manufacturing aircraft and cars respectively to inherit and implement this interface

Original address: http://bbs.phpchina.com/thread-242243-1-1.html


3. Observer pattern


The observer pattern is a behavioral pattern and is a definition A one-to-many dependency relationship between objects so that when the state of one object changes, all objects that depend on it are notified and automatically refreshed. It perfectly separates the observer object and the observed object. A list of dependencies (observers) that are interested in the principal can be maintained in a separate object (the principal). Have all observers individually implement a common Observer interface to eliminate the direct dependency between the principal and dependent objects. (I can’t understand it anyway)


used 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;
    }

    public function attach(SplObserver $observer) {
        $this->_observers->attach($observer);
    }

    public function detach(SplObserver $observer) {
        $this->_observers->detach($observer);
    }

    public function notify() {
        foreach ($this->_observers as $observer) {
            $observer->update($this);
        }
    }

    public function getName() {
        return $this->_name;
    }
}

$observer1 = new MyObserver1();
$observer2 = new MyObserver2();

$subject = new MySubject("test");

$subject->attach($observer1);
$subject->attach($observer2);

$subject->notify();

Reference original text: http://www.php.net/manual/ zh/class.splsubject.php

4. Strategy mode

In this mode, the algorithm is extracted from a complex class and can therefore be easily replaced. For example, if you want to change the way pages are ranked in search engines, Strategy mode is a good choice. Think about the parts of a search engine—one that traverses pages, one that ranks each page, and another that sorts the results based on the ranking. In complex examples, these parts are all in the same class. By using the Strategy pattern, you can put the arrangement part into another class to change the way the page is arranged without affecting the rest of the search engine's code.

Some summaries about design patterns on the PHP Internet

As a simpler example, below shows a user list class that provides a way to find a set of users based on a set of plug-and-play policies

//定义接口
interface IStrategy {
    function filter($record);
}

//实现接口方式1
class FindAfterStrategy implements IStrategy {
    private $_name;
    public function __construct($name) {
        $this->_name = $name;
    }
    public function filter($record) {
        return strcmp ( $this->_name, $record ) <= 0;
    }
}

//实现接口方式1
class RandomStrategy implements IStrategy {
    public function filter($record) {
        return rand ( 0, 1 ) >= 0.5;
    }
}

//主类
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;
    }
    
    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" 
) );
$f1 = $ul->find ( new FindAfterStrategy ( "J" ) );
print_r ( $f1 );

$f2 = $ul->find ( new RandomStrategy () );

print_r ( $f2 );

Strategy pattern is very suitable for complex data management systems or data processing systems, both of which require high flexibility in the way of data filtering, search or processing


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more