# 装饰模式 ## 一句话 In plain words 通俗易懂 > Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class. > Decorator 模式允许您通过将对象包装在 Decorator 类的对象中,在运行时动态更改对象的行为。 > **Programmatic Example 编程示例** Lets take coffee for example. First of all we have a simple coffee implementing the coffee interface 让我们以咖啡为例。首先,我们有一个简单的 coffee 实现 coffee 接口 ```php interface Coffee { public function getCost(); public function getDescription(); } class SimpleCoffee implements Coffee { public function getCost() { return 10; } public function getDescription() { return 'Simple coffee'; } } ``` We want to make the code extensible to allow options to modify it if required. Lets make some add-ons (decorators) 我们希望使代码可扩展,以允许选项在需要时对其进行修改。让我们制作一些附加组件(装饰器) ```php class MilkCoffee implements Coffee { protected $coffee; public function __construct(Coffee $coffee) { $this->coffee = $coffee; } public function getCost() { return $this->coffee->getCost() + 2; } public function getDescription() { return $this->coffee->getDescription() . ', milk'; } } class WhipCoffee implements Coffee { protected $coffee; public function __construct(Coffee $coffee) { $this->coffee = $coffee; } public function getCost() { return $this->coffee->getCost() + 5; } public function getDescription() { return $this->coffee->getDescription() . ', whip'; } } ``` ## 缺点 - 产生很多小对象,影响程序性能 - 比继承更加容易出错,排错也更难 # 外观模式 ## 一句话 Wikipedia says 维基百科说 > A facade is an object that provides a simplified interface to a larger body of code, such as a class library. > Facade 是一个对象,它为较大的代码体(如类库)提供简化的接口。 Here we have the facade 这里有门面 ``` class ComputerFacade { protected $computer; public function __construct(Computer $computer) { $this->computer = $computer; } public function turnOn() { $this->computer->getElectricShock(); $this->computer->makeSound(); $this->computer->showLoadingScreen(); $this->computer->bam(); } public function turnOff() { $this->computer->closeEverything(); $this->computer->pullCurrent(); $this->computer->sooth(); } } ``` Now to use the facade 现在使用 Facade ``` $computer = new ComputerFacade(new Computer()); $computer->turnOn(); // Ouch! Beep beep! Loading.. Ready to be used! $computer->turnOff(); // Bup bup buzzz! Haah! Zzzzz ```