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();
    我感觉装饰器模式跟策略模式差不多,细想装饰器模式是去修饰一个对象,策略模式是根据一个对象设计一个策略。
  • 相关阅读:
    SAP BI 常用TCODE
    ABAP Table Control
    Smartforms 设置纸张打印格式
    SAP库存历史库存表更新逻辑 (转)
    ABAP 调用远程rfc
    php 随机生成数字字母组合
    php错误提示 open_basedir restriction in effect 解决
    MySQL Errno : 1062 错误修复
    mysql数据库允许远程连接
    httpd.conf文件与.htaccess文件的对比
  • 原文地址:https://www.cnblogs.com/webph/p/6748051.html
Copyright © 2011-2022 走看看