按 Enter 键跳转到正文

PHP中的设计模式

PHP中的设计模式

介绍

设计模式:提供了一种广泛的可重用的方式来解决我们日常编程中常常遇见的问题。设计模式并不一定就是一个类库或者第三方框架,它们更多的表现为一种思想并且广泛地应用在系统中。它们也表现为一种模式或者模板,可以在多个不同的场景下用于解决问题。设计模式可以用于加速开发,并且将很多大的想法或者设计以一种简单地方式实现。当然,虽然设计模式在开发中很有作用,但是千万要避免在不适当的场景误用它们。

分类

按照目的分,目前常见的设计模式主要有23种,根据使用目标的不同可以分为以下三大类:

创建设计模式(Creational Patterns)(5种):用于创建对象时的设计模式。更具体一点,初始化对象流程的设计模式。当程序日益复杂时,需要更加灵活地创建对象,同时减少创建时的依赖。而创建设计模式就是解决此问题的一类设计模式。

  • 单例模式【Singleton】
  • 工厂模式【Factory】
  • 抽象工厂模式【AbstractFactory】
  • 建造者模式【Builder】
  • 原型模式【Prototype】

结构设计模式(Structural Patterns)(7种):用于继承和接口时的设计模式。结构设计模式用于新类的函数方法设计,减少不必要的类定义,减少代码的冗余。

  • 适配器模式【Adapter】
  • 桥接模式【Bridge】
  • 合成模式【Composite】
  • 装饰器模式【Decorator】
  • 门面模式【Facade】
  • 代理模式【Proxy】
  • 享元模式【Flyweight】

行为模式(Behavioral Patterns)(11种):用于方法实现以及对应算法的设计模式,同时也是最复杂的设计模式。行为设计模式不仅仅用于定义类的函数行为,同时也用于不同类之间的协议、通信。

  • 策略模式【Strategy】
  • 模板方法模式【TemplateMethod】
  • 观察者模式【Observer】
  • 迭代器模式【Iterator】
  • 责任链模式【ResponsibilityChain】
  • 命令模式【Command】
  • 备忘录模式【Memento】
  • 状态模式【State】
  • 访问者模式【Visitor】
  • 中介者模式【Mediator】
  • 解释器模式【Interpreter】

按照范围分为:类的设计模式,以及对象设计模式

  • 类的设计模式(Class patterns):用于类的具体实现的设计模式。包含了如何设计和定义类,以及父类和子类的设计模式。

  • 对象设计模式(Object patterns): 用于对象的设计模式。与类的设计模式不同,对象设计模式主要用于运行期对象的状态改变、动态行为变更等。

设计模式原则

设计模式六大原则

  • 开放封闭原则:一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。
  • 里氏替换原则:所有引用基类的地方必须能透明地使用其子类的对象.
  • 依赖倒置原则:高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖细节;细节应该依赖抽象。
  • 单一职责原则:不要存在多于一个导致类变更的原因。通俗的说,即一个类只负责一项职责。
  • 接口隔离原则:客户端不应该依赖它不需要的接口;一个类对另一个类的依赖应该建立在最小的接口上。
  • 迪米特法则:一个对象应该对其他对象保持最少的了解。

设计模式实现

1. Singleton(单例模式)

单例模式是最常见的模式之一,在Web应用的开发中,常常用于允许在运行时为某个特定的类创建仅有一个可访问的实例。

 1<?php
 2final class Mysql
 3{
 4 
 5    /**
 6     *
 7     * @var self[该属性用来保存实例]
 8     */
 9    private static $instance;
10 
11    /**
12     *
13     * @var mixed
14     */
15    public $mix;
16 
17    /**
18     * Return self instance[创建一个用来实例化对象的方法]
19     *
20     * @return self
21     */
22    public static function getInstance()
23    {
24        if (! (self::$instance instanceof self)) {
25            self::$instance = new self();
26        }
27        return self::$instance;
28    }
29 
30    /**
31     * 构造函数为private,防止创建对象
32     */
33    private function __construct()
34    {}
35 
36    /**
37     * 防止对象被复制
38     */
39    private function __clone()
40    {
41        trigger_error('Clone is not allowed !');
42    }
43}
44 
45// @test
46$firstMysql = Mysql::getInstance();
47$secondMysql = Mysql::getInstance();
48 
49$firstMysql->mix = 'ityangs_one';
50$secondMysql->mix = 'ityangs_two';
51 
52print_r($firstMysql->mix);
53// 输出: ityangs_two
54print_r($secondMysql->mix);

2. Factory(工厂模式)

工厂模式是另一种非常常用的模式,正如其名字所示:确实是对象实例的生产工厂。某些意义上,工厂模式提供了通用的方法有助于我们去获取对象,而不需要关心其具体的内在的实现。

 1<?php
 2interface SystemFactory
 3{
 4    public function createSystem($type);
 5}
 6
 7class MySystemFactory implements SystemFactory
 8{
 9    // 实现工厂方法
10    public function createSystem($type)
11    {
12        switch ($type) {
13            case 'Mac':
14                return new MacSystem();
15            case 'Win':
16                return new WinSystem();
17            case 'Linux':
18                return new LinuxSystem();
19        }
20    }
21}
22 
23class System{ /* ... */}
24class WinSystem extends System{ /* ... */}
25class MacSystem extends System{ /* ... */}
26class LinuxSystem extends System{ /* ... */}
27 
28//创建我的系统工厂
29$System_obj = new MySystemFactory();
30//用我的系统工厂分别创建不同系统对象
31var_dump($System_obj->createSystem('Mac'));//输出:object(MacSystem)#2 (0) { }
32var_dump($System_obj->createSystem('Win'));//输出:object(WinSystem)#2 (0) { }
33var_dump($System_obj->createSystem('Linux'));//输出:object(LinuxSystem)#2 (0) { }

3. AbstractFactory(抽象工厂模式)

有些情况下我们需要根据不同的选择逻辑提供不同的构造工厂,而对于多个工厂而言需要一个统一的抽象工厂:

 1<?php
 2 
 3class System{}
 4class Soft{}
 5 
 6class MacSystem extends System{}
 7class MacSoft extends Soft{}
 8 
 9class WinSystem extends System{}
10class WinSoft extends Soft{}
11 
12interface AbstractFactory {
13    public function CreateSystem();
14    public function CreateSoft();
15}
16 
17class MacFactory implements AbstractFactory{
18    public function CreateSystem(){ return new MacSystem(); }
19    public function CreateSoft(){ return new MacSoft(); }
20}
21 
22class WinFactory implements AbstractFactory{
23    public function CreateSystem(){ return new WinSystem(); }
24    public function CreateSoft(){ return new WinSoft(); }
25}
26 
27//@test:创建工厂->用该工厂生产对应的对象
28 
29//创建MacFactory工厂
30$MacFactory_obj = new MacFactory();
31//用MacFactory工厂分别创建不同对象
32var_dump($MacFactory_obj->CreateSystem());//输出:object(MacSystem)#2 (0) { }
33var_dump($MacFactory_obj->CreateSoft());// 输出:object(MacSoft)#2 (0) { }
34 
35 
36//创建WinFactory
37$WinFactory_obj = new WinFactory();
38//用WinFactory工厂分别创建不同对象
39var_dump($WinFactory_obj->CreateSystem());//输出:object(WinSystem)#3 (0) { }
40var_dump($WinFactory_obj->CreateSoft());//输出:object(WinSoft)#3 (0) { }

4. Builder(建造者模式)

建造者模式主要在于创建一些复杂的对象。将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示的设计模式;

 1<?php
 2/**
 3 * 
 4 * 产品本身
 5 */
 6class Product { 
 7    private $_parts; 
 8    public function __construct() { $this->_parts = array(); } 
 9    public function add($part) { return array_push($this->_parts, $part); }
10}
11 
12/**
13 * 建造者抽象类
14 *
15 */
16abstract class Builder {
17    public abstract function buildPart1();
18    public abstract function buildPart2();
19    public abstract function getResult();
20}
21 
22/**
23 * 
24 * 具体建造者
25 * 实现其具体方法
26 */
27class ConcreteBuilder extends Builder {  
28    private $_product;
29    public function __construct() { $this->_product = new Product(); }
30    public function buildPart1() { $this->_product->add("Part1"); } 
31    public function buildPart2() { $this->_product->add("Part2"); }
32    public function getResult() { return $this->_product; }
33}
34 /**
35  * 
36  *导演者
37  */
38class Director { 
39    public function __construct(Builder $builder) {
40        $builder->buildPart1();//导演指挥具体建造者生产产品
41        $builder->buildPart2();
42    }
43}
44 
45// client 
46$buidler = new ConcreteBuilder();
47$director = new Director($buidler);
48$product = $buidler->getResult();
49echo "<pre>";
50var_dump($product);
51echo "</pre>";
52/*输出: object(Product)#2 (1) {
53["_parts":"Product":private]=>
54array(2) {
55    [0]=>string(5) "Part1"
56    [1]=>string(5) "Part2"
57}
58} */
59?>

5. Prototype(原型模式)

有时候,部分对象需要被初始化多次。而特别是在如果初始化需要耗费大量时间与资源的时候进行预初始化并且存储下这些对象,就会用到原型模式:

 1<?php
 2/**
 3 * 
 4 * 原型接口
 5 *
 6 */
 7interface Prototype { public function copy(); }
 8 
 9/**
10 * 具体实现
11 *
12 */
13class ConcretePrototype implements Prototype{
14    private  $_name;
15    public function __construct($name) { $this->_name = $name; } 
16    public function copy() { return clone $this;}
17}
18 
19class Test {}
20 
21// client
22$object1 = new ConcretePrototype(new Test());
23var_dump($object1);//输出:object(ConcretePrototype)#1 (1) { ["_name":"ConcretePrototype":private]=> object(Test)#2 (0) { } } 
24$object2 = $object1->copy();
25var_dump($object2);//输出:object(ConcretePrototype)#3 (1) { ["_name":"ConcretePrototype":private]=> object(Test)#2 (0) { } }
26?>

6. Adapter(适配器模式)

这种模式允许使用不同的接口重构某个类,可以允许使用不同的调用方式进行调用:

 1<?php
 2/**
 3 * 第一种方式:对象适配器
 4 */
 5interface Target {
 6    public function sampleMethod1();
 7    public function sampleMethod2();
 8}
 9 
10class Adaptee {
11    public function sampleMethod1() {
12        echo '++++++++';
13    }
14}
15 
16class Adapter implements Target {
17    private $_adaptee;
18 
19    public function __construct(Adaptee $adaptee) {
20        $this->_adaptee = $adaptee;
21    }
22 
23    public function sampleMethod1() {
24        $this->_adaptee->sampleMethod1(); 
25    }
26 
27    public function sampleMethod2() {
28        echo '————————'; 
29    }
30}
31$adapter = new Adapter(new Adaptee());
32$adapter->sampleMethod1();//输出:++++++++
33$adapter->sampleMethod2();//输出:————————
34 
35 
36 
37/**
38 * 第二种方式:类适配器
39 */
40interface Target2 {
41    public function sampleMethod1();
42    public function sampleMethod2();
43}
44 
45class Adaptee2 { // 源角色
46    public function sampleMethod1() {echo '++++++++';}
47}
48 
49class Adapter2 extends Adaptee2 implements Target2 { // 适配后角色
50    public function sampleMethod2() {echo '————————';} 
51}
52 
53$adapter = new Adapter2();
54$adapter->sampleMethod1();//输出:++++++++
55$adapter->sampleMethod2();//输出:————————
56?>

7. Bridge(桥接模式)

将抽象部分与它的实现部分分离,使他们都可以独立的变抽象与它的实现分离,即抽象类和它的派生类用来实现自己的对象

 1<?php
 2/**
 3 * 
 4 *实现化角色, 给出实现化角色的接口,但不给出具体的实现。
 5 */
 6abstract class Implementor { 
 7    abstract public function operationImp();
 8}
 9 
10class ConcreteImplementorA extends Implementor { // 具体化角色A
11    public function operationImp() {echo "A";}
12}
13 
14class ConcreteImplementorB extends Implementor { // 具体化角色B
15    public function operationImp() {echo "B";}
16}
17 
18 
19/**
20 * 
21 * 抽象化角色,抽象化给出的定义,并保存一个对实现化对象的引用
22 */
23abstract class Abstraction { 
24    protected $imp; // 对实现化对象的引用
25    public function operation() {
26        $this->imp->operationImp();
27    }
28}
29class RefinedAbstraction extends Abstraction { // 修正抽象化角色, 扩展抽象化角色,改变和修正父类对抽象化的定义。
30    public function __construct(Implementor $imp) {
31        $this->imp = $imp;
32    }
33    public function operation() { $this->imp->operationImp(); }
34}
35 
36// client
37$abstraction = new RefinedAbstraction(new ConcreteImplementorA());
38$abstraction->operation();//输出:A
39$abstraction = new RefinedAbstraction(new ConcreteImplementorB());
40$abstraction->operation();//输出:B
41?>
  1. Composite(合成模式) 组合模式(Composite Pattern)有时候又叫做部分-整体模式,用于将对象组合成树形结构以表示“部分-整体”的层次关系。组合模式使得用户对单个对象和组合对象的使用具有一致性。

常见使用场景:如树形菜单、文件夹菜单、部门组织架构图等。

  1<?php
  2/**
  3 * 
  4 *安全式合成模式
  5 */
  6interface Component {
  7    public function getComposite(); //返回自己的实例
  8    public function operation();
  9}
 10 
 11class Composite implements Component { // 树枝组件角色
 12    private $_composites;
 13    public function __construct() { $this->_composites = array(); }
 14    public function getComposite() { return $this; }
 15     public function operation() {
 16         foreach ($this->_composites as $composite) {
 17            $composite->operation();
 18        }
 19     }
 20 
 21    public function add(Component $component) {  //聚集管理方法 添加一个子对象
 22        $this->_composites[] = $component;
 23    }
 24 
 25    public function remove(Component $component) { // 聚集管理方法 删除一个子对象
 26        foreach ($this->_composites as $key => $row) {
 27            if ($component == $row) { unset($this->_composites[$key]); return TRUE; }
 28        } 
 29        return FALSE;
 30    }
 31 
 32    public function getChild() { // 聚集管理方法 返回所有的子对象
 33       return $this->_composites;
 34    }
 35 
 36}
 37 
 38class Leaf implements Component {
 39    private $_name; 
 40    public function __construct($name) { $this->_name = $name; }
 41    public function operation() {}
 42    public function getComposite() {return null;}
 43}
 44 
 45// client
 46$leaf1 = new Leaf('first');
 47$leaf2 = new Leaf('second');
 48 
 49$composite = new Composite();
 50$composite->add($leaf1);
 51$composite->add($leaf2);
 52$composite->operation();
 53 
 54$composite->remove($leaf2);
 55$composite->operation();
 56 
 57 
 58 
 59 
 60 
 61 
 62/**
 63 * 
 64 *透明式合成模式
 65 */
 66interface Component { // 抽象组件角色
 67    public function getComposite(); // 返回自己的实例
 68    public function operation(); // 示例方法
 69    public function add(Component $component); // 聚集管理方法,添加一个子对象
 70    public function remove(Component $component); // 聚集管理方法 删除一个子对象
 71    public function getChild(); // 聚集管理方法 返回所有的子对象
 72}
 73 
 74class Composite implements Component { // 树枝组件角色
 75    private $_composites;
 76    public function __construct() { $this->_composites = array(); } 
 77    public function getComposite() { return $this; }
 78    public function operation() { // 示例方法,调用各个子对象的operation方法
 79        foreach ($this->_composites as $composite) {
 80            $composite->operation();
 81        }
 82    }
 83    public function add(Component $component) { // 聚集管理方法 添加一个子对象
 84        $this->_composites[] = $component;
 85    }
 86    public function remove(Component $component) { // 聚集管理方法 删除一个子对象
 87        foreach ($this->_composites as $key => $row) {
 88            if ($component == $row) { unset($this->_composites[$key]); return TRUE; }
 89        } 
 90        return FALSE;
 91    }
 92    public function getChild() { // 聚集管理方法 返回所有的子对象
 93       return $this->_composites;
 94    }
 95 
 96}
 97 
 98class Leaf implements Component {
 99    private $_name;
100    public function __construct($name) {$this->_name = $name;}
101    public function operation() {echo $this->_name."<br>";}
102    public function getComposite() { return null; }
103    public function add(Component $component) { return FALSE; }
104    public function remove(Component $component) { return FALSE; }
105    public function getChild() { return null; }
106}
107 
108// client 
109$leaf1 = new Leaf('first');
110$leaf2 = new Leaf('second');
111 
112$composite = new Composite();
113$composite->add($leaf1);
114$composite->add($leaf2);
115$composite->operation();
116 
117$composite->remove($leaf2);
118$composite->operation();
119 
120?>

9. Decorator(装饰器模式)

装饰器模式允许我们根据运行时不同的情景动态地为某个对象调用前后添加不同的行

 1<?php
 2interface Component {
 3    public function operation();
 4}
 5 
 6abstract class Decorator implements Component{ // 装饰角色 
 7    protected  $_component;
 8    public function __construct(Component $component) {
 9        $this->_component = $component;
10    }
11    public function operation() {
12        $this->_component->operation();
13    }
14}
15 
16class ConcreteDecoratorA extends Decorator { // 具体装饰类A
17    public function __construct(Component $component) {
18        parent::__construct($component);
19    } 
20    public function operation() {
21        parent::operation();    //  调用装饰类的操作
22        $this->addedOperationA();   //  新增加的操作
23    }
24    public function addedOperationA() {echo 'A加点酱油;';}
25}
26 
27class ConcreteDecoratorB extends Decorator { // 具体装饰类B
28    public function __construct(Component $component) {
29        parent::__construct($component);
30    } 
31    public function operation() {
32        parent::operation();
33        $this->addedOperationB();
34    }
35    public function addedOperationB() {echo "B加点辣椒;";}
36}
37 
38class ConcreteComponent implements Component{ //具体组件类
39    public function operation() {} 
40}
41 
42// clients
43$component = new ConcreteComponent();
44$decoratorA = new ConcreteDecoratorA($component);
45$decoratorB = new ConcreteDecoratorB($decoratorA);
46 
47$decoratorA->operation();//输出:A加点酱油;
48echo '<br>--------<br>';
49$decoratorB->operation();//输出:A加点酱油;B加点辣椒;
50?>

10. Facade(门面模式)

门面模式 (Facade)又称外观模式,用于为子系统中的一组接口提供一个一致的界面。门面模式定义了一个高层接口,这个接口使得子系统更加容易使用:引入门面角色之后,用户只需要直接与门面角色交互,用户与子系统之间的复杂关系由门面角色来实现,从而降低了系统的耦

 1<?php
 2class Camera {
 3    public function turnOn() {}
 4    public function turnOff() {}
 5    public function rotate($degrees) {}
 6}
 7 
 8class Light {
 9    public function turnOn() {}
10    public function turnOff() {}
11    public function changeBulb() {}
12}
13 
14class Sensor {
15    public function activate() {}
16    public function deactivate() {}
17    public function trigger() {}
18}
19 
20class Alarm {
21    public function activate() {}
22    public function deactivate() {}
23    public function ring() {}
24    public function stopRing() {}
25}
26 
27class SecurityFacade {
28    private $_camera1, $_camera2;
29    private $_light1, $_light2, $_light3;
30    private $_sensor;
31    private $_alarm;
32 
33    public function __construct() {
34        $this->_camera1 = new Camera();
35        $this->_camera2 = new Camera();
36 
37        $this->_light1 = new Light();
38        $this->_light2 = new Light();
39        $this->_light3 = new Light();
40 
41        $this->_sensor = new Sensor();
42        $this->_alarm = new Alarm();
43    }
44 
45    public function activate() {
46        $this->_camera1->turnOn();
47        $this->_camera2->turnOn();
48 
49        $this->_light1->turnOn();
50        $this->_light2->turnOn();
51        $this->_light3->turnOn();
52 
53        $this->_sensor->activate();
54        $this->_alarm->activate();
55    }
56 
57    public  function deactivate() {
58        $this->_camera1->turnOff();
59        $this->_camera2->turnOff();
60 
61        $this->_light1->turnOff();
62        $this->_light2->turnOff();
63        $this->_light3->turnOff();
64 
65        $this->_sensor->deactivate();
66        $this->_alarm->deactivate();
67    }
68}
69 
70 
71//client 
72$security = new SecurityFacade();
73$security->activate();
74?> 

11. Proxy(代理模式)

代理模式(Proxy)为其他对象提供一种代理以控制对这个对象的访问。使用代理模式创建代理对象,让代理对象控制目标对象的访问(目标对象可以是远程的对象、创建开销大的对象或需要安全控制的对象),并且可以在不改变目标对象的情况下添加一些额外的功能。

在某些情况下,一个客户不想或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用,并且可以通过代理对象去掉客户不能看到的内容和服务或者添加客户需要的额外服务。

经典例子就是网络代理,你想访问 Facebook 或者 Twitter ,如何绕过 GFW?找个代理

 1<?
 2abstract class Subject { // 抽象主题角色
 3    abstract public function action();
 4}
 5 
 6class RealSubject extends Subject { // 真实主题角色
 7    public function __construct() {}
 8    public function action() {}
 9}
10 
11class ProxySubject extends Subject { // 代理主题角色
12    private $_real_subject = NULL;
13    public function __construct() {}
14 
15    public function action() {
16        $this->_beforeAction();
17        if (is_null($this->_real_subject)) {
18            $this->_real_subject = new RealSubject();
19        }
20        $this->_real_subject->action();
21        $this->_afterAction();
22    }
23 
24    private function _beforeAction() {
25        echo '在action前,我想干点啥....';
26    }
27 
28    private function _afterAction() {
29         echo '在action后,我还想干点啥....';
30    }
31}
32 
33// client
34$subject = new ProxySubject();
35$subject->action();//输出:在action前,我想干点啥....在action后,我还想干点啥....
36?> 

12. Flyweight(享元模式)

运用共享技术有效的支持大量细粒度的对象

享元模式变化的是对象的存储开销

享元模式中主要角色:

抽象享元(Flyweight)角色:此角色是所有的具体享元类的超类,为这些类规定出需要实现的公共接口。那些需要外运状态的操作可以通过调用商业以参数形式传入

具体享元(ConcreteFlyweight)角色:实现Flyweight接口,并为内部状态(如果有的话)拉回存储空间。ConcreteFlyweight对象必须是可共享的。它所存储的状态必须是内部的

不共享的具体享元(UnsharedConcreteFlyweight)角色:并非所有的Flyweight子类都需要被共享。Flyweigth使共享成为可能,但它并不强制共享

享元工厂(FlyweightFactory)角色:负责创建和管理享元角色。本角色必须保证享元对象可能被系统适当地共享

客户端(Client)角色:本角色需要维护一个对所有享元对象的引用。本角色需要自行存储所有享元对象的外部状态

享元模式的优点:

Flyweight模式可以大幅度地降低内存中对象的数量

享元模式的缺点:

Flyweight模式使得系统更加复杂

Flyweight模式将享元对象的状态外部化,而读取外部状态使得运行时间稍微变长

享元模式适用场景:

当一下情况成立时使用Flyweight模式:

1 一个应用程序使用了大量的对象

2 完全由于使用大量的对象,造成很大的存储开销

3 对象的大多数状态都可变为外部状态

4 如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象

5 应用程序不依赖于对象标识

 1<?php
 2abstract class Resources{
 3    public $resource=null;
 4 
 5    abstract public function operate();
 6}
 7 
 8class unShareFlyWeight extends Resources{
 9    public function __construct($resource_str) {
10        $this->resource = $resource_str;
11    }
12 
13    public function operate(){
14        echo $this->resource."<br>";
15    }
16}
17 
18class shareFlyWeight extends Resources{
19    private $resources = array();
20 
21    public function get_resource($resource_str){
22        if(isset($this->resources[$resource_str])) {
23            return $this->resources[$resource_str];
24        }else {
25            return $this->resources[$resource_str] = $resource_str;
26        }
27    }
28 
29    public function operate(){
30        foreach ($this->resources as $key => $resources) {
31            echo $key.":".$resources."<br>";
32        }
33    }
34}
35 
36 
37// client
38$flyweight = new shareFlyWeight();
39$flyweight->get_resource('a');
40$flyweight->operate();
41 
42 
43$flyweight->get_resource('b');
44$flyweight->operate();
45 
46$flyweight->get_resource('c');
47$flyweight->operate();
48 
49// 不共享的对象,单独调用
50$uflyweight = new unShareFlyWeight('A');
51$uflyweight->operate();
52 
53$uflyweight = new unShareFlyWeight('B');
54$uflyweight->operate();
55/* 输出:
56 a:a
57 a:a
58 b:b
59 a:a
60 b:b
61 c:c
62 A
63 B */

13. Strategy(策略模式)

策略模式主要为了让客户类能够更好地使用某些算法而不需要知道其具体的实现。

 1<?php
 2interface Strategy { // 抽象策略角色,以接口实现
 3    public function do_method(); // 算法接口
 4}
 5 
 6class ConcreteStrategyA implements Strategy { // 具体策略角色A 
 7    public function do_method() {
 8        echo 'do method A';
 9    }
10}
11 
12class ConcreteStrategyB implements Strategy { // 具体策略角色B 
13    public function do_method() {
14        echo 'do method B';
15    }
16}
17 
18class ConcreteStrategyC implements Strategy { // 具体策略角色C
19    public function do_method() {
20        echo 'do method C';
21    }
22}
23 
24 
25class Question{ // 环境角色
26    private $_strategy;
27 
28    public function __construct(Strategy $strategy) {
29        $this->_strategy = $strategy;
30    } 
31    public function handle_question() {
32        $this->_strategy->do_method();
33    }
34}
35 
36// client
37$strategyA = new ConcreteStrategyA();
38$question = new Question($strategyA);
39$question->handle_question();//输出do method A
40 
41$strategyB = new ConcreteStrategyB();
42$question = new Question($strategyB);
43$question->handle_question();//输出do method B
44 
45$strategyC = new ConcreteStrategyC();
46$question = new Question($strategyC);
47$question->handle_question();//输出do method C
48?>

14. TemplateMethod(模板方法模式)

模板模式准备一个抽象类,将部分逻辑以具体方法以及具体构造形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现。先制定一个顶级逻辑框架,而将逻辑的细节留给具体的子类去实现。

 1<?php
 2abstract class AbstractClass { // 抽象模板角色
 3    public function templateMethod() { // 模板方法 调用基本方法组装顶层逻辑
 4        $this->primitiveOperation1();
 5        $this->primitiveOperation2();
 6    }
 7    abstract protected function primitiveOperation1(); // 基本方法
 8    abstract protected function primitiveOperation2();
 9}
10 
11class ConcreteClass extends AbstractClass { // 具体模板角色
12    protected function primitiveOperation1() {}
13    protected function primitiveOperation2(){}
14 
15}
16 
17$class = new ConcreteClass();
18$class->templateMethod();
19?>

15. Observer(观察者模式)

某个对象可以被设置为是可观察的,只要通过某种方式允许其他对象注册为观察者。每当被观察的对象改变时,会发送信息给观察者。

 1<?php
 2 
 3    interface IObserver{
 4        function onSendMsg( $sender, $args );
 5        function getName();
 6    }
 7 
 8    interface IObservable{
 9        function addObserver( $observer );
10    }
11 
12    class UserList implements IObservable{
13        private $_observers = array();
14 
15        public function sendMsg( $name ){
16            foreach( $this->_observers as $obs ){
17                $obs->onSendMsg( $this, $name );
18            }
19        }
20 
21        public function addObserver( $observer ){
22            $this->_observers[]= $observer;
23        }
24 
25        public function removeObserver($observer_name) {
26            foreach($this->_observers as $index => $observer) {
27                if ($observer->getName() === $observer_name) {
28                    array_splice($this->_observers, $index, 1);
29                    return;
30                }
31            }
32        }
33    }
34 
35    class UserListLogger implements IObserver{
36        public function onSendMsg( $sender, $args ){
37            echo( "'$args' send to UserListLogger\n" );
38        }
39 
40        public function getName(){
41            return 'UserListLogger';
42        }
43    }
44 
45    class OtherObserver implements IObserver{
46        public function onSendMsg( $sender, $args ){
47            echo( "'$args' send to OtherObserver\n" );
48        }
49 
50        public function getName(){
51            return 'OtherObserver';
52        }
53    }
54 
55 
56    $ul = new UserList();//被观察者
57    $ul->addObserver( new UserListLogger() );//增加观察者
58    $ul->addObserver( new OtherObserver() );//增加观察者
59    $ul->sendMsg( "Jack" );//发送消息到观察者
60 
61    $ul->removeObserver('UserListLogger');//移除观察者
62    $ul->sendMsg("hello");//发送消息到观察者
63 
64 /*    输出:'Jack' send to UserListLogger 'Jack' send to OtherObserver 'hello' send to OtherObserver */
65?>

16. Iterator(迭代器模式)

迭代器模式 (Iterator),又叫做游标(Cursor)模式。提供一种方法访问一个容器(Container)对象中各个元素,而又不需暴露该对象的内部细节。

当你需要访问一个聚合对象,而且不管这些对象是什么都需要遍历的时候,就应该考虑使用迭代器模式。另外,当需要对聚集有多种方式遍历时,可以考虑去使用迭代器模式。迭代器模式为遍历不同的聚集结构提供如开始、下一个、是否结束、当前哪一项等统一的接口。

php标准库(SPL)中提供了迭代器接口 Iterator,要实现迭代器模式,实现该接口即可。

  1<?php
  2class sample implements Iterator {
  3    private $_items ;
  4 
  5    public function __construct(&$data) {
  6        $this->_items = $data;
  7    }
  8    public function current() {
  9        return current($this->_items);
 10    }
 11 
 12    public function next() {
 13        next($this->_items);   
 14    }
 15 
 16    public function key() {
 17        return key($this->_items);
 18    }
 19 
 20    public function rewind() {
 21        reset($this->_items);
 22    }
 23 
 24    public function valid() {                                                                              
 25        return ($this->current() !== FALSE);
 26    }
 27}
 28 
 29// client
 30$data = array(1, 2, 3, 4, 5);
 31$sa = new sample($data);
 32foreach ($sa AS $key => $row) {
 33    echo $key, ' ', $row, '<br />';
 34}
 35/* 输出:
 360 1
 371 2
 382 3
 393 4
 404 5 */
 41//Yii FrameWork Demo
 42class CMapIterator implements Iterator {
 43/**
 44* @var array the data to be iterated through
 45*/
 46    private $_d;
 47/**
 48* @var array list of keys in the map
 49*/
 50    private $_keys;
 51/**
 52* @var mixed current key
 53*/
 54    private $_key;
 55 
 56/**
 57* Constructor.
 58* @param array the data to be iterated through
 59*/
 60    public function __construct(&$data) {
 61        $this->_d=&$data;
 62        $this->_keys=array_keys($data);
 63    }
 64 
 65/**
 66* Rewinds internal array pointer.
 67* This method is required by the interface Iterator.
 68*/
 69    public function rewind() {                                                                                 
 70        $this->_key=reset($this->_keys);
 71    }
 72 
 73/**
 74* Returns the key of the current array element.
 75* This method is required by the interface Iterator.
 76* @return mixed the key of the current array element
 77*/
 78    public function key() {
 79        return $this->_key;
 80    }
 81 
 82/**
 83* Returns the current array element.
 84* This method is required by the interface Iterator.
 85* @return mixed the current array element
 86*/
 87    public function current() {
 88        return $this->_d[$this->_key];
 89    }
 90 
 91/**
 92* Moves the internal pointer to the next array element.
 93* This method is required by the interface Iterator.
 94*/
 95    public function next() {
 96        $this->_key=next($this->_keys);
 97    }
 98 
 99/**
100* Returns whether there is an element at current position.
101* This method is required by the interface Iterator.
102* @return boolean
103*/
104    public function valid() {
105        return $this->_key!==false;
106    }
107}
108 
109$data = array('s1' => 11, 's2' => 22, 's3' => 33);
110$it = new CMapIterator($data);
111foreach ($it as $row) {
112    echo $row, '<br />';
113}
114 
115/* 输出:
11611
11722
11833 */
119?>

17. ResponsibilityChain(责任链模式)

这种模式有另一种称呼:控制链模式。它主要由一系列对于某些命令的处理器构成,每个查询会在处理器构成的责任链中传递,在每个交汇点由处理器判断是否需要对它们进行响应与处理。每次的处理程序会在有处理器处理这些请求时暂停。

 1<?php
 2 
 3abstract class Responsibility { // 抽象责任角色
 4    protected $next; // 下一个责任角色
 5 
 6    public function setNext(Responsibility $l) {
 7        $this->next = $l;
 8        return $this;
 9    }
10    abstract public function operate(); // 操作方法
11}
12 
13class ResponsibilityA extends Responsibility {
14    public function __construct() {}
15    public function operate(){
16        if (false == is_null($this->next)) {
17            $this->next->operate();
18            echo 'Res_A start'."<br>";
19        }
20    }
21}
22 
23class ResponsibilityB extends Responsibility {
24    public function __construct() {}
25    public function operate(){
26        if (false == is_null($this->next)) {
27            $this->next->operate();
28            echo 'Res_B start';
29        }
30    }
31}
32 
33$res_a = new ResponsibilityA();
34$res_b = new ResponsibilityB();
35$res_a->setNext($res_b);
36$res_a->operate();//输出:Res_A start
37?>

18. Command(命令模式)

命令模式:在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”。但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将“行为请求者”与“行为实现者”解耦?将一组行为抽象为对象,实现二者之间的松耦合。这就是命令模式。 角色分析: 抽象命令:定义命令的接口,声明执行的方法。 具体命令:命令接口实现对象,是“虚”的实现;通常会持有接收者,并调用接收者的功能来完成命令要执行的操作。 命令接收者:接收者,真正执行命令的对象。任何类都可能成为一个接收者,只要它能够实现命令要求实现的相应功能。 控制者:要求命令对象执行请求,通常会持有命令对象,可以持有很多的命令对象。这个是客户端真正触发命令并要求命令执行相应操作的地方,也就是说相当于使用命令对象的入口。

 1      <?php
 2interface Command { // 命令角色
 3    public function execute(); // 执行方法
 4}
 5 
 6class ConcreteCommand implements Command { // 具体命令方法 
 7    private $_receiver; 
 8    public function __construct(Receiver $receiver) {
 9        $this->_receiver = $receiver;
10    }
11    public function execute() {
12        $this->_receiver->action();
13    }
14}
15 
16class Receiver { // 接收者角色
17    private $_name;
18    public function __construct($name) {
19        $this->_name = $name;
20    }
21    public function action() {
22        echo 'receive some cmd:'.$this->_name;
23    }
24}
25 
26class Invoker { // 请求者角色
27    private $_command; 
28    public function __construct(Command $command) {
29        $this->_command = $command;
30    }
31    public function action() {
32        $this->_command->execute();
33    }
34}
35 
36$receiver = new Receiver('hello world');
37$command = new ConcreteCommand($receiver);
38$invoker = new Invoker($command);
39$invoker->action();//输出:receive some cmd:hello world
40?>

19. 备忘录模式

备忘录模式又叫做快照模式(Snapshot)或 Token 模式,备忘录模式的用意是在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样就可以在合适的时候将该对象恢复到原先保存的状态。

我们在编程的时候,经常需要保存对象的中间状态,当需要的时候,可以恢复到这个状态。比如,我们使用Eclipse进行编程时,假如编写失误(例如不小心误删除了几行代码),我们希望返回删除前的状态,便可以使用Ctrl+Z来进行返回。这时我们便可以使用备忘录模式来实现。

备忘录模式所涉及的角色有三个:备忘录(Memento)角色、发起人(Originator)角色、负责人(Caretaker)角色。

这三个角色的职责分别是:

发起人:记录当前时刻的内部状态,负责定义哪些属于备份范围的状态,负责创建和恢复备忘录数据。 备忘录:负责存储发起人对象的内部状态,在需要的时候提供发起人需要的内部状态。 管理角色:对备忘录进行管理,保存和提供备忘录。

 1<?php
 2 
 3class Originator { // 发起人(Originator)角色
 4    private $_state;
 5    public function __construct() {
 6        $this->_state = '';
 7    }
 8    public function createMemento() { // 创建备忘录
 9        return new Memento($this->_state);
10    }
11    public function restoreMemento(Memento $memento) { // 将发起人恢复到备忘录对象记录的状态上
12        $this->_state = $memento->getState();
13    }
14    public function setState($state) { $this->_state = $state; } 
15    public function getState() { return $this->_state; }
16    public function showState() {
17        echo $this->_state;echo "<br>";
18    }
19 
20}
21 
22class Memento { // 备忘录(Memento)角色 
23    private $_state;
24    public function __construct($state) {
25        $this->setState($state);
26    }
27    public function getState() { return $this->_state; } 
28    public function setState($state) { $this->_state = $state;}
29}
30 
31class Caretaker { // 负责人(Caretaker)角色 
32    private $_memento;
33    public function getMemento() { return $this->_memento; } 
34    public function setMemento(Memento $memento) { $this->_memento = $memento; }
35}
36 
37// client
38/* 创建目标对象 */
39$org = new Originator();
40$org->setState('open');
41$org->showState();
42 
43/* 创建备忘 */
44$memento = $org->createMemento();
45 
46/* 通过Caretaker保存此备忘 */
47$caretaker = new Caretaker();
48$caretaker->setMemento($memento);
49 
50/* 改变目标对象的状态 */
51$org->setState('close');
52$org->showState();
53 
54$org->restoreMemento($memento);
55$org->showState();
56 
57/* 改变目标对象的状态 */
58$org->setState('close');
59$org->showState();
60 
61/* 还原操作 */
62$org->restoreMemento($caretaker->getMemento());
63$org->showState();
64/* 输出:
65open
66close
67open
68close
69open */
70?>

20. State(状态模式)

状态模式当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。状态模式主要解决的是当控制一个对象状态的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判断逻辑简化。

角色: 上下文环境(Work):它定义了客户程序需要的接口并维护一个具体状态角色的实例,将与状态相关的操作委托给当前的具体对象来处理。 抽象状态(State):定义一个接口以封装使用上下文环境的的一个特定状态相关的行为。 具体状态(AmState):实现抽象状态定义的接口。

 1         <?php
 2interface State { // 抽象状态角色
 3    public function handle(Context $context); // 方法示例
 4}
 5 
 6class ConcreteStateA implements State { // 具体状态角色A
 7    private static $_instance = null;
 8    private function __construct() {}
 9    public static function getInstance() { // 静态工厂方法,返还此类的唯一实例
10        if (is_null(self::$_instance)) {
11            self::$_instance = new ConcreteStateA();
12        }
13        return self::$_instance;
14    }
15 
16    public function handle(Context $context) {
17        echo 'concrete_a'."<br>";
18        $context->setState(ConcreteStateB::getInstance());
19    }
20 
21}
22 
23class ConcreteStateB implements State { // 具体状态角色B
24    private static $_instance = null;
25    private function __construct() {}
26    public static function getInstance() {
27        if (is_null(self::$_instance)) {
28            self::$_instance = new ConcreteStateB();
29        }
30        return self::$_instance;
31    }
32 
33    public function handle(Context $context) {
34        echo 'concrete_b'."<br>";
35        $context->setState(ConcreteStateA::getInstance());
36    }
37}
38 
39class Context { // 环境角色 
40    private $_state;
41    public function __construct() { // 默认为stateA
42        $this->_state = ConcreteStateA::getInstance();
43    }
44    public function setState(State $state) {
45        $this->_state = $state;
46    }
47    public function request() {
48        $this->_state->handle($this);
49    }
50}
51 
52// client
53$context = new Context();
54$context->request();
55$context->request();
56$context->request();
57$context->request();
58/* 输出:
59concrete_a
60concrete_b
61concrete_a
62concrete_b */
63?>

21. Visitor(访问者模式)

访问者模式是一种行为型模式,访问者表示一个作用于某对象结构中各元素的操作。它可以在不修改各元素类的前提下定义作用于这些元素的新操作,即动态的增加具体访问者角色。

访问者模式利用了双重分派。先将访问者传入元素对象的Accept方法中,然后元素对象再将自己传入访问者,之后访问者执行元素的相应方法。

主要角色

抽象访问者角色(Visitor):为该对象结构(ObjectStructure)中的每一个具体元素提供一个访问操作接口。该操作接口的名字和参数标识了 要访问的具体元素角色。这样访问者就可以通过该元素角色的特定接口直接访问它。 具体访问者角色(ConcreteVisitor):实现抽象访问者角色接口中针对各个具体元素角色声明的操作。 抽象节点(Node)角色:该接口定义一个accept操作接受具体的访问者。 具体节点(Node)角色:实现抽象节点角色中的accept操作。 对象结构角色(ObjectStructure):这是使用访问者模式必备的角色。它要具备以下特征:能枚举它的元素;可以提供一个高层的接口以允许该访问者访问它的元素;可以是一个复合(组合模式)或是一个集合,如一个列表或一个无序集合(在PHP中我们使用数组代替,因为PHP中的数组本来就是一个可以放置任何类型数据的集合) 适用性

访问者模式多用在聚集类型多样的情况下。在普通的形式下必须判断每个元素是属于什么类型然后进行相应的操作,从而诞生出冗长的条件转移语句。而访问者模式则可以比较好的解决这个问题。对每个元素统一调用element−>accept(vistor)即可。 访问者模式多用于被访问的类结构比较稳定的情况下,即不会随便添加子类。访问者模式允许被访问结构添加新的方法。

 1<?php
 2interface Visitor { // 抽象访问者角色
 3    public function visitConcreteElementA(ConcreteElementA $elementA);
 4    public function visitConcreteElementB(concreteElementB $elementB);
 5}
 6 
 7interface Element { // 抽象节点角色
 8    public function accept(Visitor $visitor);
 9}
10 
11class ConcreteVisitor1 implements Visitor { // 具体的访问者1
12    public function visitConcreteElementA(ConcreteElementA $elementA) {}
13    public function visitConcreteElementB(ConcreteElementB $elementB) {}
14}
15 
16class ConcreteVisitor2 implements Visitor { // 具体的访问者2
17    public function visitConcreteElementA(ConcreteElementA $elementA) {}
18    public function visitConcreteElementB(ConcreteElementB $elementB) {}
19}
20 
21class ConcreteElementA implements Element { // 具体元素A
22    private $_name;
23    public function __construct($name) { $this->_name = $name; } 
24    public function getName() { return $this->_name; }
25    public function accept(Visitor $visitor) { // 接受访问者调用它针对该元素的新方法
26        $visitor->visitConcreteElementA($this);
27    }
28}
29 
30class ConcreteElementB implements Element { // 具体元素B
31    private $_name; 
32    public function __construct($name) { $this->_name = $name;}
33    public function getName() { return $this->_name; }
34    public function accept(Visitor $visitor) { // 接受访问者调用它针对该元素的新方法
35        $visitor->visitConcreteElementB($this);
36    }
37}
38 
39class ObjectStructure { // 对象结构 即元素的集合
40    private $_collection; 
41    public function __construct() { $this->_collection = array(); } 
42    public function attach(Element $element) {
43        return array_push($this->_collection, $element);
44    }
45    public function detach(Element $element) {
46        $index = array_search($element, $this->_collection);
47        if ($index !== FALSE) {
48            unset($this->_collection[$index]);
49        }
50        return $index;
51    }
52    public function accept(Visitor $visitor) {
53        foreach ($this->_collection as $element) {
54            $element->accept($visitor);
55        }
56    }
57}
58 
59// client
60$elementA = new ConcreteElementA("ElementA");
61$elementB = new ConcreteElementB("ElementB");
62$elementA2 = new ConcreteElementB("ElementA2");
63$visitor1 = new ConcreteVisitor1();
64$visitor2 = new ConcreteVisitor2();
65 
66$os = new ObjectStructure();
67$os->attach($elementA);
68$os->attach($elementB);
69$os->attach($elementA2);
70$os->detach($elementA);
71$os->accept($visitor1);
72$os->accept($visitor2);
73?>

22. Mediator(中介者模式)

中介者模式用于开发一个对象,这个对象能够在类似对象相互之间不直接相互的情况下传送或者调解对这些对象的集合的修改。 一般处理具有类似属性,需要保持同步的非耦合对象时,最佳的做法就是中介者模式。PHP中不是特别常用的设计模式。

 1<?php
 2abstract class Mediator { // 中介者角色
 3    abstract public function send($message,$colleague); 
 4} 
 5 
 6abstract class Colleague { // 抽象对象
 7    private $_mediator = null; 
 8    public function __construct($mediator) { 
 9        $this->_mediator = $mediator; 
10    } 
11    public function send($message) { 
12        $this->_mediator->send($message,$this); 
13    } 
14    abstract public function notify($message); 
15} 
16 
17class ConcreteMediator extends Mediator { // 具体中介者角色
18    private $_colleague1 = null; 
19    private $_colleague2 = null; 
20    public function send($message,$colleague) {
21        //echo $colleague->notify($message);
22        if($colleague == $this->_colleague1) { 
23            $this->_colleague1->notify($message); 
24        } else { 
25            $this->_colleague2->notify($message); 
26        } 
27    }
28    public function set($colleague1,$colleague2) { 
29        $this->_colleague1 = $colleague1; 
30        $this->_colleague2 = $colleague2; 
31    } 
32} 
33 
34class Colleague1 extends Colleague { // 具体对象角色
35    public function notify($message) {
36        echo 'colleague1:'.$message."<br>";
37    } 
38} 
39 
40class Colleague2 extends Colleague { // 具体对象角色
41    public function notify($message) { 
42        echo 'colleague2:'.$message."<br>";
43    } 
44} 
45 
46// client
47$objMediator = new ConcreteMediator(); 
48$objC1 = new Colleague1($objMediator); 
49$objC2 = new Colleague2($objMediator); 
50$objMediator->set($objC1,$objC2); 
51$objC1->send("to c2 from c1"); //输出:colleague1:to c2 from c1
52$objC2->send("to c1 from c2"); //输出:colleague2:to c1 from c2
53?> 

23. Interpreter(解释器模式)

给定一个语言, 定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。 角色: 环境角色(PlayContent):定义解释规则的全局信息。 抽象解释器(Empress):定义了部分解释具体实现,封装了一些由具体解释器实现的接口。 具体解释器(MusicNote):实现抽象解释器的接口,进行具体的解释执行。

 1<?php
 2class Expression { //抽象表示
 3    function interpreter($str) { 
 4        return $str; 
 5    } 
 6} 
 7 
 8class ExpressionNum extends Expression { //表示数字
 9    function interpreter($str) { 
10        switch($str) { 
11            case "0": return "零"; 
12            case "1": return "一"; 
13            case "2": return "二"; 
14            case "3": return "三"; 
15            case "4": return "四"; 
16            case "5": return "五"; 
17            case "6": return "六"; 
18            case "7": return "七"; 
19            case "8": return "八"; 
20            case "9": return "九"; 
21        } 
22    } 
23} 
24 
25class ExpressionCharater extends Expression { //表示字符
26    function interpreter($str) { 
27        return strtoupper($str); 
28    } 
29} 
30 
31class Interpreter { //解释器
32    function execute($string) { 
33        $expression = null; 
34        for($i = 0;$i<strlen($string);$i++) { 
35            $temp = $string[$i]; 
36            switch(true) { 
37                case is_numeric($temp): $expression = new ExpressionNum(); break; 
38                default: $expression = new ExpressionCharater(); 
39            } 
40            echo $expression->interpreter($temp);
41            echo "<br>"; 
42        } 
43    } 
44} 
45 
46//client
47$obj = new Interpreter(); 
48$obj->execute("123s45abc"); 
49/* 输出:
50515253S
545556A
57B
58C */
59?>

参考文章: PHP 中最全的设计模式(23种)

发表评论