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

 

装饰器模式中主要角色

 

抽象组件角色(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();


我要穿衣服了
输出:

穿裤子
穿体恤