首页 > Web开发 > 详细

php 23种设计模式 - 设计模式简介以及分类

时间:2020-03-14 13:24:12      阅读:103      评论:0      收藏:0      [点我收藏+]

PhpDesignPatterns 【PHP 中的设计模式】

一、 Introduction【介绍】

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

二、 Category【分类】

根据目的和范围,设计模式可以分为五类。
按照目的分为:创建设计模式,结构设计模式,以及行为设计模式。
按照范围分为:类的设计模式,以及对象设计模式。

1. 按照目的分,目前常见的设计模式主要有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】

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

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

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

三、 DesignPatternsPrinciple【设计模式原则】

设计模式六大原则

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

四、 Realization【设计模式实现】

Creational Patterns(创建设计模式)

1. Singleton(单例模式)

  • Singleton(单例模式):单例模式是最常见的模式之一,在Web应用的开发中,常常用于允许在运行时为某个特定的类创建仅有一个可访问的实例。
  1.  
    <?php
  2.  
     
  3.  
    /**
  4.  
    * Singleton class[单例模式]
  5.  
    * @author ITYangs<ityangs@163.com>
  6.  
    */
  7.  
    final classMysql
  8.  
    {
  9.  
     
  10.  
    /**
  11.  
    *
  12.  
    * @var self[该属性用来保存实例]
  13.  
    */
  14.  
    private static $instance;
  15.  
     
  16.  
    /**
  17.  
    *
  18.  
    * @var mixed
  19.  
    */
  20.  
    public $mix;
  21.  
     
  22.  
    /**
  23.  
    * Return self instance[创建一个用来实例化对象的方法]
  24.  
    *
  25.  
    * @return self
  26.  
    */
  27.  
    public static functiongetInstance()
  28.  
    {
  29.  
    if (! (self::$instance instanceof self)) {
  30.  
    self::$instance = new self();
  31.  
    }
  32.  
    return self::$instance;
  33.  
    }
  34.  
     
  35.  
    /**
  36.  
    * 构造函数为private,防止创建对象
  37.  
    */
  38.  
    private function__construct()
  39.  
    {}
  40.  
     
  41.  
    /**
  42.  
    * 防止对象被复制
  43.  
    */
  44.  
    private function__clone()
  45.  
    {
  46.  
    trigger_error(‘Clone is not allowed !‘);
  47.  
    }
  48.  
    }
  49.  
     
  50.  
    // @test
  51.  
    $firstMysql = Mysql::getInstance();
  52.  
    $secondMysql = Mysql::getInstance();
  53.  
     
  54.  
    $firstMysql->mix = ‘ityangs_one‘;
  55.  
    $secondMysql->mix = ‘ityangs_two‘;
  56.  
     
  57.  
    print_r($firstMysql->mix);
  58.  
    // 输出: ityangs_two
  59.  
    print_r($secondMysql->mix);
  60.  
    // 输出: ityangs_two

在很多情况下,需要为系统中的多个类创建单例的构造方式,这样,可以建立一个通用的抽象父工厂方法:

  1.  
    <?php
  2.  
    /**
  3.  
    * Singleton class[单例模式:多个类创建单例的构造方式]
  4.  
    * @author ITYangs<ityangs@163.com>
  5.  
    */
  6.  
    abstract classFactoryAbstract{
  7.  
     
  8.  
    protected static $instances = array();
  9.  
     
  10.  
    public static functiongetInstance(){
  11.  
    $className = self::getClassName();
  12.  
    if (!(self::$instances[$className] instanceof $className)) {
  13.  
    self::$instances[$className] = new $className();
  14.  
    }
  15.  
    return self::$instances[$className];
  16.  
    }
  17.  
     
  18.  
    public static functionremoveInstance(){
  19.  
    $className = self::getClassName();
  20.  
    if (array_key_exists($className, self::$instances)) {
  21.  
    unset(self::$instances[$className]);
  22.  
    }
  23.  
    }
  24.  
     
  25.  
    final protected static functiongetClassName(){
  26.  
    return get_called_class();
  27.  
    }
  28.  
     
  29.  
    protected function__construct(){ }
  30.  
     
  31.  
    final protected function__clone(){ }
  32.  
    }
  33.  
     
  34.  
    abstract classFactoryextendsFactoryAbstract{
  35.  
     
  36.  
    final public static functiongetInstance(){
  37.  
    return parent::getInstance();
  38.  
    }
  39.  
     
  40.  
    final public static functionremoveInstance(){
  41.  
    parent::removeInstance();
  42.  
    }
  43.  
    }
  44.  
    // @test
  45.  
     
  46.  
    classFirstProductextendsFactory{
  47.  
    public $a = [];
  48.  
    }
  49.  
    classSecondProductextendsFirstProduct{
  50.  
    }
  51.  
     
  52.  
    FirstProduct::getInstance()->a[] = 1;
  53.  
    SecondProduct::getInstance()->a[] = 2;
  54.  
    FirstProduct::getInstance()->a[] = 11;
  55.  
    SecondProduct::getInstance()->a[] = 22;
  56.  
     
  57.  
    print_r(FirstProduct::getInstance()->a);
  58.  
    // Array ( [0] => 1 [1] => 11 )
  59.  
    print_r(SecondProduct::getInstance()->a);
  60.  
    // Array ( [0] => 2 [1] => 22 )

2. Factory(工厂模式)

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

  1.  
    <?php
  2.  
     
  3.  
    /**
  4.  
    * Factory class[工厂模式]
  5.  
    * @author ITYangs<ityangs@163.com>
  6.  
    */
  7.  
    interface SystemFactory
  8.  
    {
  9.  
    public function createSystem($type);
  10.  
    }
  11.  
     
  12.  
    classMySystemFactoryimplementsSystemFactory
  13.  
    {
  14.  
    // 实现工厂方法
  15.  
    public function createSystem($type)
  16.  
    {
  17.  
    switch ($type) {
  18.  
    case ‘Mac‘:
  19.  
    return new MacSystem();
  20.  
    case ‘Win‘:
  21.  
    return new WinSystem();
  22.  
    case ‘Linux‘:
  23.  
    return new LinuxSystem();
  24.  
    }
  25.  
    }
  26.  
    }
  27.  
     
  28.  
    classSystem{ /* ... */}
  29.  
    classWinSystemextendsSystem{ /* ... */}
  30.  
    classMacSystemextendsSystem{ /* ... */}
  31.  
    classLinuxSystemextendsSystem{ /* ... */}
  32.  
     
  33.  
    //创建我的系统工厂
  34.  
    $System_obj = new MySystemFactory();
  35.  
    //用我的系统工厂分别创建不同系统对象
  36.  
    var_dump($System_obj->createSystem(‘Mac‘));//输出:object(MacSystem)#2 (0) { }
  37.  
    var_dump($System_obj->createSystem(‘Win‘));//输出:object(WinSystem)#2 (0) { }
  38.  
    var_dump($System_obj->createSystem(‘Linux‘));//输出:object(LinuxSystem)#2 (0) { }

3. AbstractFactory(抽象工厂模式)

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

  1.  
    <?php
  2.  
     
  3.  
    classSystem{}
  4.  
    classSoft{}
  5.  
     
  6.  
    classMacSystemextendsSystem{}
  7.  
    classMacSoftextendsSoft{}
  8.  
     
  9.  
    classWinSystemextendsSystem{}
  10.  
    classWinSoftextendsSoft{}
  11.  
     
  12.  
     
  13.  
    /**
  14.  
    * AbstractFactory class[抽象工厂模式]
  15.  
    * @author ITYangs<ityangs@163.com>
  16.  
    */
  17.  
    interfaceAbstractFactory{
  18.  
    public functionCreateSystem();
  19.  
    public functionCreateSoft();
  20.  
    }
  21.  
     
  22.  
    classMacFactoryimplementsAbstractFactory{
  23.  
    public functionCreateSystem(){ return new MacSystem(); }
  24.  
    public functionCreateSoft(){ return new MacSoft(); }
  25.  
    }
  26.  
     
  27.  
    classWinFactoryimplementsAbstractFactory{
  28.  
    public functionCreateSystem(){ return new WinSystem(); }
  29.  
    public functionCreateSoft(){ return new WinSoft(); }
  30.  
    }
  31.  
     
  32.  
     
  33.  
     
  34.  
     
  35.  
     
  36.  
     
  37.  
    //@test:创建工厂->用该工厂生产对应的对象
  38.  
     
  39.  
    //创建MacFactory工厂
  40.  
    $MacFactory_obj = new MacFactory();
  41.  
    //用MacFactory工厂分别创建不同对象
  42.  
    var_dump($MacFactory_obj->CreateSystem());//输出:object(MacSystem)#2 (0) { }
  43.  
    var_dump($MacFactory_obj->CreateSoft());// 输出:object(MacSoft)#2 (0) { }
  44.  
     
  45.  
     
  46.  
    //创建WinFactory
  47.  
    $WinFactory_obj = new WinFactory();
  48.  
    //用WinFactory工厂分别创建不同对象
  49.  
    var_dump($WinFactory_obj->CreateSystem());//输出:object(WinSystem)#3 (0) { }
  50.  
    var_dump($WinFactory_obj->CreateSoft());//输出:object(WinSoft)#3 (0) { }

4. Builder(建造者模式)

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

结构图:
技术分享图片

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

5. Prototype(原型模式)

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

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

Structural Patterns(结构设计模式)

6. Adapter(适配器模式)

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

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

7. Bridge(桥接模式)

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

桥接与适配器模式的关系(适配器模式上面已讲解):
桥接属于聚合关系,两者关联 但不继承
适配器属于组合关系,适配者需要继承源

聚合关系:A对象可以包含B对象 但B对象不是A对象的一部分

  1.  
    <?php
  2.  
    /**
  3.  
    *
  4.  
    *实现化角色, 给出实现化角色的接口,但不给出具体的实现。
  5.  
    */
  6.  
    abstractclassImplementor{
  7.  
    abstractpublicfunctionoperationImp();
  8.  
    }
  9.  
     
  10.  
    classConcreteImplementorAextendsImplementor{ // 具体化角色A
  11.  
    publicfunctionoperationImp(){echo"A";}
  12.  
    }
  13.  
     
  14.  
    classConcreteImplementorBextendsImplementor{ // 具体化角色B
  15.  
    publicfunctionoperationImp(){echo"B";}
  16.  
    }
  17.  
     
  18.  
     
  19.  
    /**
  20.  
    *
  21.  
    * 抽象化角色,抽象化给出的定义,并保存一个对实现化对象的引用
  22.  
    */
  23.  
    abstractclassAbstraction{
  24.  
    protected $imp; // 对实现化对象的引用
  25.  
    publicfunctionoperation(){
  26.  
    $this->imp->operationImp();
  27.  
    }
  28.  
    }
  29.  
    classRefinedAbstractionextendsAbstraction{ // 修正抽象化角色, 扩展抽象化角色,改变和修正父类对抽象化的定义。
  30.  
    publicfunction__construct(Implementor $imp){
  31.  
    $this->imp = $imp;
  32.  
    }
  33.  
    publicfunctionoperation(){ $this->imp->operationImp(); }
  34.  
    }
  35.  
     
  36.  
     
  37.  
     
  38.  
     
  39.  
     
  40.  
    // client
  41.  
    $abstraction = new RefinedAbstraction(new ConcreteImplementorA());
  42.  
    $abstraction->operation();//输出:A
  43.  
    $abstraction = new RefinedAbstraction(new ConcreteImplementorB());
  44.  
    $abstraction->operation();//输出:B
  45.  
    ?>

8. Composite(合成模式)

组合模式(Composite Pattern)有时候又叫做部分-整体模式,用于将对象组合成树形结构以表示“部分-整体”的层次关系。组合模式使得用户对单个对象和组合对象的使用具有一致性。

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

  1.  
    <?php
  2.  
    /**
  3.  
    *
  4.  
    *安全式合成模式
  5.  
    */
  6.  
    interfaceComponent{
  7.  
    publicfunctiongetComposite(); //返回自己的实例
  8.  
    publicfunctionoperation();
  9.  
    }
  10.  
     
  11.  
    classCompositeimplementsComponent{ // 树枝组件角色
  12.  
    private $_composites;
  13.  
    publicfunction__construct(){ $this->_composites = array(); }
  14.  
    publicfunctiongetComposite(){ return$this; }
  15.  
    publicfunctionoperation(){
  16.  
    foreach ($this->_composites as $composite) {
  17.  
    $composite->operation();
  18.  
    }
  19.  
    }
  20.  
     
  21.  
    publicfunctionadd(Component $component){ //聚集管理方法 添加一个子对象
  22.  
    $this->_composites[] = $component;
  23.  
    }
  24.  
     
  25.  
    publicfunctionremove(Component $component){ // 聚集管理方法 删除一个子对象
  26.  
    foreach ($this->_composites as $key => $row) {
  27.  
    if ($component == $row) { unset($this->_composites[$key]); returnTRUE; }
  28.  
    }
  29.  
    returnFALSE;
  30.  
    }
  31.  
     
  32.  
    publicfunctiongetChild(){ // 聚集管理方法 返回所有的子对象
  33.  
    return$this->_composites;
  34.  
    }
  35.  
     
  36.  
    }
  37.  
     
  38.  
    classLeafimplementsComponent{
  39.  
    private $_name;
  40.  
    publicfunction__construct($name){ $this->_name = $name; }
  41.  
    publicfunctionoperation(){}
  42.  
    publicfunctiongetComposite(){returnnull;}
  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.  
    */
  66.  
    interfaceComponent{ // 抽象组件角色
  67.  
    publicfunctiongetComposite(); // 返回自己的实例
  68.  
    publicfunctionoperation(); // 示例方法
  69.  
    publicfunctionadd(Component $component); // 聚集管理方法,添加一个子对象
  70.  
    publicfunctionremove(Component $component); // 聚集管理方法 删除一个子对象
  71.  
    publicfunctiongetChild(); // 聚集管理方法 返回所有的子对象
  72.  
    }
  73.  
     
  74.  
    classCompositeimplementsComponent{ // 树枝组件角色
  75.  
    private $_composites;
  76.  
    publicfunction__construct(){ $this->_composites = array(); }
  77.  
    publicfunctiongetComposite(){ return$this; }
  78.  
    publicfunctionoperation(){ // 示例方法,调用各个子对象的operation方法
  79.  
    foreach ($this->_composites as $composite) {
  80.  
    $composite->operation();
  81.  
    }
  82.  
    }
  83.  
    publicfunctionadd(Component $component){ // 聚集管理方法 添加一个子对象
  84.  
    $this->_composites[] = $component;
  85.  
    }
  86.  
    publicfunctionremove(Component $component){ // 聚集管理方法 删除一个子对象
  87.  
    foreach ($this->_composites as $key => $row) {
  88.  
    if ($component == $row) { unset($this->_composites[$key]); returnTRUE; }
  89.  
    }
  90.  
    returnFALSE;
  91.  
    }
  92.  
    publicfunctiongetChild(){ // 聚集管理方法 返回所有的子对象
  93.  
    return$this->_composites;
  94.  
    }
  95.  
     
  96.  
    }
  97.  
     
  98.  
    classLeafimplementsComponent{
  99.  
    private $_name;
  100.  
    publicfunction__construct($name){$this->_name = $name;}
  101.  
    publicfunctionoperation(){echo$this->_name."<br>";}
  102.  
    publicfunctiongetComposite(){ returnnull; }
  103.  
    publicfunctionadd(Component $component){ returnFALSE; }
  104.  
    publicfunctionremove(Component $component){ returnFALSE; }
  105.  
    publicfunctiongetChild(){ returnnull; }
  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
  2.  
    interfaceComponent{
  3.  
    publicfunctionoperation();
  4.  
    }
  5.  
     
  6.  
    abstractclassDecoratorimplementsComponent{ // 装饰角色
  7.  
    protected $_component;
  8.  
    publicfunction__construct(Component $component){
  9.  
    $this->_component = $component;
  10.  
    }
  11.  
    publicfunctionoperation(){
  12.  
    $this->_component->operation();
  13.  
    }
  14.  
    }
  15.  
     
  16.  
    classConcreteDecoratorAextendsDecorator{ // 具体装饰类A
  17.  
    publicfunction__construct(Component $component){
  18.  
    parent::__construct($component);
  19.  
    }
  20.  
    publicfunctionoperation(){
  21.  
    parent::operation(); // 调用装饰类的操作
  22.  
    $this->addedOperationA(); // 新增加的操作
  23.  
    }
  24.  
    publicfunctionaddedOperationA(){echo‘A加点酱油;‘;}
  25.  
    }
  26.  
     
  27.  
    classConcreteDecoratorBextendsDecorator{ // 具体装饰类B
  28.  
    publicfunction__construct(Component $component){
  29.  
    parent::__construct($component);
  30.  
    }
  31.  
    publicfunctionoperation(){
  32.  
    parent::operation();
  33.  
    $this->addedOperationB();
  34.  
    }
  35.  
    publicfunctionaddedOperationB(){echo"B加点辣椒;";}
  36.  
    }
  37.  
     
  38.  
    classConcreteComponentimplementsComponent{ //具体组件类
  39.  
    publicfunctionoperation(){}
  40.  
    }
  41.  
     
  42.  
    // clients
  43.  
    $component = new ConcreteComponent();
  44.  
    $decoratorA = new ConcreteDecoratorA($component);
  45.  
    $decoratorB = new ConcreteDecoratorB($decoratorA);
  46.  
     
  47.  
    $decoratorA->operation();//输出:A加点酱油;
  48.  
    echo‘<br>--------<br>‘;
  49.  
    $decoratorB->operation();//输出:A加点酱油;B加点辣椒;
  50.  
    ?>

10. Facade(门面模式)

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

  1.  
    <?php
  2.  
    classCamera{
  3.  
    publicfunctionturnOn(){}
  4.  
    publicfunctionturnOff(){}
  5.  
    publicfunctionrotate($degrees){}
  6.  
    }
  7.  
     
  8.  
    classLight{
  9.  
    publicfunctionturnOn(){}
  10.  
    publicfunctionturnOff(){}
  11.  
    publicfunctionchangeBulb(){}
  12.  
    }
  13.  
     
  14.  
    classSensor{
  15.  
    publicfunctionactivate(){}
  16.  
    publicfunctiondeactivate(){}
  17.  
    publicfunctiontrigger(){}
  18.  
    }
  19.  
     
  20.  
    classAlarm{
  21.  
    publicfunctionactivate(){}
  22.  
    publicfunctiondeactivate(){}
  23.  
    publicfunctionring(){}
  24.  
    publicfunctionstopRing(){}
  25.  
    }
  26.  
     
  27.  
    classSecurityFacade{
  28.  
    private $_camera1, $_camera2;
  29.  
    private $_light1, $_light2, $_light3;
  30.  
    private $_sensor;
  31.  
    private $_alarm;
  32.  
     
  33.  
    publicfunction__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.  
    publicfunctionactivate(){
  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.  
    publicfunctiondeactivate(){
  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.  
    <?
  2.  
    abstractclassSubject{ // 抽象主题角色
  3.  
    abstractpublicfunctionaction();
  4.  
    }
  5.  
     
  6.  
    classRealSubjectextendsSubject{ // 真实主题角色
  7.  
    publicfunction__construct(){}
  8.  
    publicfunctionaction(){}
  9.  
    }
  10.  
     
  11.  
    classProxySubjectextendsSubject{ // 代理主题角色
  12.  
    private $_real_subject = NULL;
  13.  
    publicfunction__construct(){}
  14.  
     
  15.  
    publicfunctionaction(){
  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.  
    privatefunction_beforeAction(){
  25.  
    echo‘在action前,我想干点啥....‘;
  26.  
    }
  27.  
     
  28.  
    privatefunction_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
  2.  
    abstract classResources{
  3.  
    public $resource=null;
  4.  
     
  5.  
    abstract public functionoperate();
  6.  
    }
  7.  
     
  8.  
    classunShareFlyWeightextendsResources{
  9.  
    public function__construct($resource_str){
  10.  
    $this->resource = $resource_str;
  11.  
    }
  12.  
     
  13.  
    public functionoperate(){
  14.  
    echo $this->resource."<br>";
  15.  
    }
  16.  
    }
  17.  
     
  18.  
    classshareFlyWeightextendsResources{
  19.  
    private $resources = array();
  20.  
     
  21.  
    public functionget_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 functionoperate(){
  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 */

Behavioral Patterns(行为模式)

13. Strategy(策略模式)

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

  1.  
    <?php
  2.  
    interfaceStrategy{ // 抽象策略角色,以接口实现
  3.  
    publicfunctiondo_method(); // 算法接口
  4.  
    }
  5.  
     
  6.  
    classConcreteStrategyAimplementsStrategy{ // 具体策略角色A
  7.  
    publicfunctiondo_method(){
  8.  
    echo‘do method A‘;
  9.  
    }
  10.  
    }
  11.  
     
  12.  
    classConcreteStrategyBimplementsStrategy{ // 具体策略角色B
  13.  
    publicfunctiondo_method(){
  14.  
    echo‘do method B‘;
  15.  
    }
  16.  
    }
  17.  
     
  18.  
    classConcreteStrategyCimplementsStrategy{ // 具体策略角色C
  19.  
    publicfunctiondo_method(){
  20.  
    echo‘do method C‘;
  21.  
    }
  22.  
    }
  23.  
     
  24.  
     
  25.  
    classQuestion{ // 环境角色
  26.  
    private $_strategy;
  27.  
     
  28.  
    publicfunction__construct(Strategy $strategy){
  29.  
    $this->_strategy = $strategy;
  30.  
    }
  31.  
    publicfunctionhandle_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
  2.  
    abstractclassAbstractClass{ // 抽象模板角色
  3.  
    publicfunctiontemplateMethod(){ // 模板方法 调用基本方法组装顶层逻辑
  4.  
    $this->primitiveOperation1();
  5.  
    $this->primitiveOperation2();
  6.  
    }
  7.  
    abstractprotectedfunctionprimitiveOperation1(); // 基本方法
  8.  
    abstractprotectedfunctionprimitiveOperation2();
  9.  
    }
  10.  
     
  11.  
    classConcreteClassextendsAbstractClass{ // 具体模板角色
  12.  
    protectedfunctionprimitiveOperation1(){}
  13.  
    protectedfunctionprimitiveOperation2(){}
  14.  
     
  15.  
    }
  16.  
     
  17.  
    $class = new ConcreteClass();
  18.  
    $class->templateMethod();
  19.  
    ?>

15. Observer(观察者模式)

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

  1.  
    <?php
  2.  
     
  3.  
    interfaceIObserver{
  4.  
    functiononSendMsg( $sender, $args );
  5.  
    functiongetName();
  6.  
    }
  7.  
     
  8.  
    interfaceIObservable{
  9.  
    functionaddObserver( $observer );
  10.  
    }
  11.  
     
  12.  
    classUserListimplementsIObservable{
  13.  
    private $_observers = array();
  14.  
     
  15.  
    publicfunctionsendMsg( $name ){
  16.  
    foreach( $this->_observers as $obs ){
  17.  
    $obs->onSendMsg( $this, $name );
  18.  
    }
  19.  
    }
  20.  
     
  21.  
    publicfunctionaddObserver( $observer ){
  22.  
    $this->_observers[]= $observer;
  23.  
    }
  24.  
     
  25.  
    publicfunctionremoveObserver($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.  
    classUserListLoggerimplementsIObserver{
  36.  
    publicfunctiononSendMsg( $sender, $args ){
  37.  
    echo( "‘$args‘ send to UserListLogger\n" );
  38.  
    }
  39.  
     
  40.  
    publicfunctiongetName(){
  41.  
    return‘UserListLogger‘;
  42.  
    }
  43.  
    }
  44.  
     
  45.  
    classOtherObserverimplementsIObserver{
  46.  
    publicfunctiononSendMsg( $sender, $args ){
  47.  
    echo( "‘$args‘ send to OtherObserver\n" );
  48.  
    }
  49.  
     
  50.  
    publicfunctiongetName(){
  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
  2.  
    classsampleimplementsIterator{
  3.  
    private $_items ;
  4.  
     
  5.  
    publicfunction__construct(&$data){
  6.  
    $this->_items = $data;
  7.  
    }
  8.  
    publicfunctioncurrent(){
  9.  
    return current($this->_items);
  10.  
    }
  11.  
     
  12.  
    publicfunctionnext(){
  13.  
    next($this->_items);
  14.  
    }
  15.  
     
  16.  
    publicfunctionkey(){
  17.  
    return key($this->_items);
  18.  
    }
  19.  
     
  20.  
    publicfunctionrewind(){
  21.  
    reset($this->_items);
  22.  
    }
  23.  
     
  24.  
    publicfunctionvalid(){
  25.  
    return ($this->current() !== FALSE);
  26.  
    }
  27.  
    }
  28.  
     
  29.  
    // client
  30.  
    $data = array(1, 2, 3, 4, 5);
  31.  
    $sa = new sample($data);
  32.  
    foreach ($sa AS $key => $row) {
  33.  
    echo $key, ‘ ‘, $row, ‘<br />‘;
  34.  
    }
  35.  
    /* 输出:
  36.  
    0 1
  37.  
    1 2
  38.  
    2 3
  39.  
    3 4
  40.  
    4 5 */
  41.  
     
  42.  
    //Yii FrameWork Demo
  43.  
    classCMapIteratorimplementsIterator{
  44.  
    /**
  45.  
    * @var array the data to be iterated through
  46.  
    */
  47.  
    private $_d;
  48.  
    /**
  49.  
    * @var array list of keys in the map
  50.  
    */
  51.  
    private $_keys;
  52.  
    /**
  53.  
    * @var mixed current key
  54.  
    */
  55.  
    private $_key;
  56.  
     
  57.  
    /**
  58.  
    * Constructor.
  59.  
    * @param array the data to be iterated through
  60.  
    */
  61.  
    publicfunction__construct(&$data){
  62.  
    $this->_d=&$data;
  63.  
    $this->_keys=array_keys($data);
  64.  
    }
  65.  
     
  66.  
    /**
  67.  
    * Rewinds internal array pointer.
  68.  
    * This method is required by the interface Iterator.
  69.  
    */
  70.  
    publicfunctionrewind(){
  71.  
    $this->_key=reset($this->_keys);
  72.  
    }
  73.  
     
  74.  
    /**
  75.  
    * Returns the key of the current array element.
  76.  
    * This method is required by the interface Iterator.
  77.  
    * @return mixed the key of the current array element
  78.  
    */
  79.  
    publicfunctionkey(){
  80.  
    return$this->_key;
  81.  
    }
  82.  
     
  83.  
    /**
  84.  
    * Returns the current array element.
  85.  
    * This method is required by the interface Iterator.
  86.  
    * @return mixed the current array element
  87.  
    */
  88.  
    publicfunctioncurrent(){
  89.  
    return$this->_d[$this->_key];
  90.  
    }
  91.  
     
  92.  
    /**
  93.  
    * Moves the internal pointer to the next array element.
  94.  
    * This method is required by the interface Iterator.
  95.  
    */
  96.  
    publicfunctionnext(){
  97.  
    $this->_key=next($this->_keys);
  98.  
    }
  99.  
     
  100.  
    /**
  101.  
    * Returns whether there is an element at current position.
  102.  
    * This method is required by the interface Iterator.
  103.  
    * @return boolean
  104.  
    */
  105.  
    publicfunctionvalid(){
  106.  
    return$this->_key!==false;
  107.  
    }
  108.  
    }
  109.  
     
  110.  
    $data = array(‘s1‘ => 11, ‘s2‘ => 22, ‘s3‘ => 33);
  111.  
    $it = new CMapIterator($data);
  112.  
    foreach ($it as $row) {
  113.  
    echo $row, ‘<br />‘;
  114.  
    }
  115.  
     
  116.  
    /* 输出:
  117.  
    11
  118.  
    22
  119.  
    33 */
  120.  
    ?>

 

17. ResponsibilityChain(责任链模式)

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

  1.  
    <?php
  2.  
     
  3.  
    abstractclassResponsibility{ // 抽象责任角色
  4.  
    protected $next; // 下一个责任角色
  5.  
     
  6.  
    publicfunctionsetNext(Responsibility $l){
  7.  
    $this->next = $l;
  8.  
    return$this;
  9.  
    }
  10.  
    abstractpublicfunctionoperate(); // 操作方法
  11.  
    }
  12.  
     
  13.  
    classResponsibilityAextendsResponsibility{
  14.  
    publicfunction__construct(){}
  15.  
    publicfunctionoperate(){
  16.  
    if (false == is_null($this->next)) {
  17.  
    $this->next->operate();
  18.  
    echo‘Res_A start‘."<br>";
  19.  
    }
  20.  
    }
  21.  
    }
  22.  
     
  23.  
    classResponsibilityBextendsResponsibility{
  24.  
    publicfunction__construct(){}
  25.  
    publicfunctionoperate(){
  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
  2.  
    interfaceCommand{ // 命令角色
  3.  
    publicfunctionexecute(); // 执行方法
  4.  
    }
  5.  
     
  6.  
    classConcreteCommandimplementsCommand{ // 具体命令方法
  7.  
    private $_receiver;
  8.  
    publicfunction__construct(Receiver $receiver){
  9.  
    $this->_receiver = $receiver;
  10.  
    }
  11.  
    publicfunctionexecute(){
  12.  
    $this->_receiver->action();
  13.  
    }
  14.  
    }
  15.  
     
  16.  
    classReceiver{ // 接收者角色
  17.  
    private $_name;
  18.  
    publicfunction__construct($name){
  19.  
    $this->_name = $name;
  20.  
    }
  21.  
    publicfunctionaction(){
  22.  
    echo‘receive some cmd:‘.$this->_name;
  23.  
    }
  24.  
    }
  25.  
     
  26.  
    classInvoker{ // 请求者角色
  27.  
    private $_command;
  28.  
    publicfunction__construct(Command $command){
  29.  
    $this->_command = $command;
  30.  
    }
  31.  
    publicfunctionaction(){
  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.  
    ?>

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

我们在编程的时候,经常需要保存对象的中间状态,当需要的时候,可以恢复到这个状态。比如,我们使用Eclipse进行编程时,假如编写失误(例如不小心误删除了几行代码),我们希望返回删除前的状态,便可以使用Ctrl+Z来进行返回。这时我们便可以使用备忘录模式来实现。
UML:
技术分享图片
备忘录模式所涉及的角色有三个:备忘录(Memento)角色、发起人(Originator)角色、负责人(Caretaker)角色。

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

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

  1.  
    <?php
  2.  
     
  3.  
    classOriginator{ // 发起人(Originator)角色
  4.  
    private $_state;
  5.  
    publicfunction__construct(){
  6.  
    $this->_state = ‘‘;
  7.  
    }
  8.  
    publicfunctioncreateMemento(){ // 创建备忘录
  9.  
    returnnew Memento($this->_state);
  10.  
    }
  11.  
    publicfunctionrestoreMemento(Memento $memento){ // 将发起人恢复到备忘录对象记录的状态上
  12.  
    $this->_state = $memento->getState();
  13.  
    }
  14.  
    publicfunctionsetState($state){ $this->_state = $state; }
  15.  
    publicfunctiongetState(){ return$this->_state; }
  16.  
    publicfunctionshowState(){
  17.  
    echo$this->_state;echo"<br>";
  18.  
    }
  19.  
     
  20.  
    }
  21.  
     
  22.  
    classMemento{ // 备忘录(Memento)角色
  23.  
    private $_state;
  24.  
    publicfunction__construct($state){
  25.  
    $this->setState($state);
  26.  
    }
  27.  
    publicfunctiongetState(){ return$this->_state; }
  28.  
    publicfunctionsetState($state){ $this->_state = $state;}
  29.  
    }
  30.  
     
  31.  
    classCaretaker{ // 负责人(Caretaker)角色
  32.  
    private $_memento;
  33.  
    publicfunctiongetMemento(){ return$this->_memento; }
  34.  
    publicfunctionsetMemento(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.  
    /* 输出:
  65.  
    open
  66.  
    close
  67.  
    open
  68.  
    close
  69.  
    open */
  70.  
    ?>

20. State(状态模式)

状态模式当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。状态模式主要解决的是当控制一个对象状态的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判断逻辑简化。
UML类图:
技术分享图片
角色:
上下文环境(Work):它定义了客户程序需要的接口并维护一个具体状态角色的实例,将与状态相关的操作委托给当前的具体对象来处理。
抽象状态(State):定义一个接口以封装使用上下文环境的的一个特定状态相关的行为。
具体状态(AmState):实现抽象状态定义的接口。

  1.  
    <?php
  2.  
    interfaceState{ // 抽象状态角色
  3.  
    publicfunctionhandle(Context $context); // 方法示例
  4.  
    }
  5.  
     
  6.  
    classConcreteStateAimplementsState{ // 具体状态角色A
  7.  
    privatestatic $_instance = null;
  8.  
    privatefunction__construct(){}
  9.  
    publicstaticfunctiongetInstance(){ // 静态工厂方法,返还此类的唯一实例
  10.  
    if (is_null(self::$_instance)) {
  11.  
    self::$_instance = new ConcreteStateA();
  12.  
    }
  13.  
    returnself::$_instance;
  14.  
    }
  15.  
     
  16.  
    publicfunctionhandle(Context $context){
  17.  
    echo‘concrete_a‘."<br>";
  18.  
    $context->setState(ConcreteStateB::getInstance());
  19.  
    }
  20.  
     
  21.  
    }
  22.  
     
  23.  
    classConcreteStateBimplementsState{ // 具体状态角色B
  24.  
    privatestatic $_instance = null;
  25.  
    privatefunction__construct(){}
  26.  
    publicstaticfunctiongetInstance(){
  27.  
    if (is_null(self::$_instance)) {
  28.  
    self::$_instance = new ConcreteStateB();
  29.  
    }
  30.  
    returnself::$_instance;
  31.  
    }
  32.  
     
  33.  
    publicfunctionhandle(Context $context){
  34.  
    echo‘concrete_b‘."<br>";
  35.  
    $context->setState(ConcreteStateA::getInstance());
  36.  
    }
  37.  
    }
  38.  
     
  39.  
    classContext{ // 环境角色
  40.  
    private $_state;
  41.  
    publicfunction__construct(){ // 默认为stateA
  42.  
    $this->_state = ConcreteStateA::getInstance();
  43.  
    }
  44.  
    publicfunctionsetState(State $state){
  45.  
    $this->_state = $state;
  46.  
    }
  47.  
    publicfunctionrequest(){
  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.  
    /* 输出:
  59.  
    concrete_a
  60.  
    concrete_b
  61.  
    concrete_a
  62.  
    concrete_b */
  63.  
    ?>

21. Visitor(访问者模式)

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

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

主要角色

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

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

  1.  
    <?php
  2.  
    interfaceVisitor{ // 抽象访问者角色
  3.  
    publicfunctionvisitConcreteElementA(ConcreteElementA $elementA);
  4.  
    publicfunctionvisitConcreteElementB(concreteElementB $elementB);
  5.  
    }
  6.  
     
  7.  
    interfaceElement{ // 抽象节点角色
  8.  
    publicfunctionaccept(Visitor $visitor);
  9.  
    }
  10.  
     
  11.  
    classConcreteVisitor1implementsVisitor{ // 具体的访问者1
  12.  
    publicfunctionvisitConcreteElementA(ConcreteElementA $elementA){}
  13.  
    publicfunctionvisitConcreteElementB(ConcreteElementB $elementB){}
  14.  
    }
  15.  
     
  16.  
    classConcreteVisitor2implementsVisitor{ // 具体的访问者2
  17.  
    publicfunctionvisitConcreteElementA(ConcreteElementA $elementA){}
  18.  
    publicfunctionvisitConcreteElementB(ConcreteElementB $elementB){}
  19.  
    }
  20.  
     
  21.  
    classConcreteElementAimplementsElement{ // 具体元素A
  22.  
    private $_name;
  23.  
    publicfunction__construct($name){ $this->_name = $name; }
  24.  
    publicfunctiongetName(){ return$this->_name; }
  25.  
    publicfunctionaccept(Visitor $visitor){ // 接受访问者调用它针对该元素的新方法
  26.  
    $visitor->visitConcreteElementA($this);
  27.  
    }
  28.  
    }
  29.  
     
  30.  
    classConcreteElementBimplementsElement{ // 具体元素B
  31.  
    private $_name;
  32.  
    publicfunction__construct($name){ $this->_name = $name;}
  33.  
    publicfunctiongetName(){ return$this->_name; }
  34.  
    publicfunctionaccept(Visitor $visitor){ // 接受访问者调用它针对该元素的新方法
  35.  
    $visitor->visitConcreteElementB($this);
  36.  
    }
  37.  
    }
  38.  
     
  39.  
    classObjectStructure{ // 对象结构 即元素的集合
  40.  
    private $_collection;
  41.  
    publicfunction__construct(){ $this->_collection = array(); }
  42.  
    publicfunctionattach(Element $element){
  43.  
    return array_push($this->_collection, $element);
  44.  
    }
  45.  
    publicfunctiondetach(Element $element){
  46.  
    $index = array_search($element, $this->_collection);
  47.  
    if ($index !== FALSE) {
  48.  
    unset($this->_collection[$index]);
  49.  
    }
  50.  
    return $index;
  51.  
    }
  52.  
    publicfunctionaccept(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
  2.  
    abstractclassMediator{ // 中介者角色
  3.  
    abstractpublicfunctionsend($message,$colleague);
  4.  
    }
  5.  
     
  6.  
    abstractclassColleague{ // 抽象对象
  7.  
    private $_mediator = null;
  8.  
    publicfunction__construct($mediator){
  9.  
    $this->_mediator = $mediator;
  10.  
    }
  11.  
    publicfunctionsend($message){
  12.  
    $this->_mediator->send($message,$this);
  13.  
    }
  14.  
    abstractpublicfunctionnotify($message);
  15.  
    }
  16.  
     
  17.  
    classConcreteMediatorextendsMediator{ // 具体中介者角色
  18.  
    private $_colleague1 = null;
  19.  
    private $_colleague2 = null;
  20.  
    publicfunctionsend($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.  
    publicfunctionset($colleague1,$colleague2){
  29.  
    $this->_colleague1 = $colleague1;
  30.  
    $this->_colleague2 = $colleague2;
  31.  
    }
  32.  
    }
  33.  
     
  34.  
    classColleague1extendsColleague{ // 具体对象角色
  35.  
    publicfunctionnotify($message){
  36.  
    echo‘colleague1:‘.$message."<br>";
  37.  
    }
  38.  
    }
  39.  
     
  40.  
    classColleague2extendsColleague{ // 具体对象角色
  41.  
    publicfunctionnotify($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
  2.  
    classExpression{ //抽象表示
  3.  
    functioninterpreter($str){
  4.  
    return $str;
  5.  
    }
  6.  
    }
  7.  
     
  8.  
    classExpressionNumextendsExpression{ //表示数字
  9.  
    functioninterpreter($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.  
     
  25.  
    classExpressionCharaterextendsExpression{ //表示字符
  26.  
    functioninterpreter($str){
  27.  
    return strtoupper($str);
  28.  
    }
  29.  
    }
  30.  
     
  31.  
    classInterpreter{ //解释器
  32.  
    functionexecute($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.  
    /* 输出:
  50.  
  51.  
  52.  
  53.  
    S
  54.  
  55.  
  56.  
    A
  57.  
    B
  58.  
    C */
  59.  
    ?>
 
 
G
M
T
发布了68 篇原创文章 · 获赞 18 · 访问量 18万+

php 23种设计模式 - 设计模式简介以及分类

原文:https://www.cnblogs.com/doseoer/p/12490965.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!