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();
    我感觉装饰器模式跟策略模式差不多,细想装饰器模式是去修饰一个对象,策略模式是根据一个对象设计一个策略。
  • 相关阅读:
    HDU 5583 Kingdom of Black and White 水题
    HDU 5578 Friendship of Frog 水题
    Codeforces Round #190 (Div. 2) E. Ciel the Commander 点分治
    hdu 5594 ZYB's Prime 最大流
    hdu 5593 ZYB's Tree 树形dp
    hdu 5592 ZYB's Game 树状数组
    hdu 5591 ZYB's Game 博弈论
    HDU 5590 ZYB's Biology 水题
    cdoj 1256 昊昊爱运动 预处理/前缀和
    cdoj 1255 斓少摘苹果 贪心
  • 原文地址:https://www.cnblogs.com/webph/p/6748051.html
Copyright © 2011-2022 走看看