zoukankan      html  css  js  c++  java
  • PHP 装饰器模式

    装饰器模式:是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。

    装饰器模式中主要角色

    抽象组件角色(Component):定义一个对象接口,以规范准备接受附加责任的对象,即可以给这些对象动态地添加职责。

    具体组件角色(ConcreteComponent) :被装饰者,定义一个将要被装饰增加功能的类。可以给这个类的对象添加一些职责

    抽象装饰器(Decorator):维持一个指向构件Component对象的实例,并定义一个与抽象组件角色Component接口一致的接口

    具体装饰器角色(ConcreteDecorator):向组件添加职责。

    【原型模式PHP示例】

    interface Component{                             # 抽象组件角色
        public function display();
    }
    
    
    class Person implements Component {    # 具体主键  被装饰者
    
        public function display()
        {
            echo "我要穿衣服了<br/>";
        }
    
    }
    
    
    class Clothes  implements Component {   # 抽象装饰者
    
        protected $obj;
    
        public function __construct($obj)
        {
            $this->obj = $obj;
        }
    
        public function display()
        {
            if($this->obj){
                $this->obj->display();
            }
        }
    }
    
    
    class Trousers extends Clothes{           # 具体装饰者
        public function display()
        {
            parent::display();
            echo "穿裤子<br/>";
        }
    }
    
    class Tshirt extends Clothes{
        public function display()
        {
            parent::display();
            echo "穿体恤<br/>";
        }
    }
    
    $person = new  Person();
    $person = new Trousers($person);
    $person = new Tshirt($person);
    $person->display();


    输出:

    我要穿衣服了
    穿裤子
    穿体恤

  • 相关阅读:
    sql注入漏洞与防范
    微信小程序-工具,弹出当前系统代理不是安全代理处理方法
    微信小程序-02 小程序关注组件
    微信小程序-01 小数保留二位
    http 转hhttps
    php 函数-ksort
    iOS 原生二维码扫描
    iOS 打包错误 all-product-headers.yaml' not found
    iOS Tableview点击cell 会往上跳
    WKWebView 使用
  • 原文地址:https://www.cnblogs.com/moxiaoan/p/6252273.html
Copyright © 2011-2022 走看看