zoukankan      html  css  js  c++  java
  • 设计模式之装饰器模式

    设计思想

    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();
    我感觉装饰器模式跟策略模式差不多,细想装饰器模式是去修饰一个对象,策略模式是根据一个对象设计一个策略。
  • 相关阅读:
    网络流
    KMP算法
    光现象
    物理学习须知
    声现象
    常见物理量测量方法
    洛谷 P1373 小a和uim之大逃离
    洛谷 P1242 新汉诺塔
    电磁现象
    磁化
  • 原文地址:https://www.cnblogs.com/webph/p/6748051.html
Copyright © 2011-2022 走看看