大头

设计模式之装饰器模式

设计思想

  1. 装饰器模式,可以动态添加修改类的功能
  2. 一个类提供了一项功能,如果在修改并添加额外的功能,传统的编程模式,需要编写一个子类继承他,并实现类的方法。
  3. 使用装饰器模式,仅需要在运行是添加一个装饰器对象实现就,可以实现最大的灵活性。

实现

定义装饰器接口
interface  Decorator{
    public  function  change();
}
创建装饰器
class BackgroundDecorator implements  Decorator {
    public function change()
    {
        // TODO: Implement showContent() method.
        echo "装饰器二";
    }
}
class FontDecorator implements  Decorator {
    public function change()
    {
        // TODO: Implement showContent() method.
        echo "装饰器一";
    }
}

在Advertisement中实现装饰器

class  Advertisement{
    //存放装饰器
    protected  static  $decorators ;
    //添加装饰器
    public static  function addDecorator( \Decorator $decorator){
        self::$decorators[] = $decorator;
    }
    //调用装饰器的方法
    public static  function  completeDecorator(){
        foreach (self::$decorators as $decorator){
            $decorator->change();
        }
    }
    public  function dosomething(){
       // ....
    }
}

$advertisment  = new Advertisement();
$advertisment::addDecorator(new BackgroundDecorator());
$advertisment::addDecorator(new FontDecorator());
$advertisment::completeDecorator();
我感觉装饰器模式跟策略模式差不多,细想装饰器模式是去修饰一个对象,策略模式是根据一个对象设计一个策略。
posted @ 2017-04-22 15:50  and大头  阅读(168)  评论(0编辑  收藏  举报

大头