The decorator mode is also called the decorator mode. The decoration mode is to dynamically extend the functionality of an object without changing the original class file and using inheritance. It wraps the real object by creating a wrapping object, that is, decoration.
UML class diagram:
Character:
Interface of component objects: responsibilities can be dynamically added to these objects
The parent class of all decorators: needs to define an interface consistent with the component interface and hold a Component object, which is actually the decorated object.
Specific decorator class: implements specific functions to be added to the decorated object. Used to decorate a specific component object or another specific decorator object.
Specific code:
<!--?php /** * Created by PhpStorm. * User: Jiang * Date: 2015/5/3 * Time: 11:11 */ /**组件对象接口 * Interface IComponent */ interface IComponent { function Display(); } /**待装饰对象 * Class Person */ class Person implements IComponent { private $name; function __construct($name) { $this--->name=$name; } function Display() { echo 装扮的:{$this->name} ; } } /**所有装饰器父类 * Class Clothes */ class Clothes implements IComponent { protected $component; function Decorate(IComponent $component) { $this->component=$component; } function Display() { if(!empty($this->component)) { $this->component->Display(); } } } //------------------------------具体装饰器---------------- class PiXie extends Clothes { function Display() { echo 皮鞋 ; parent::Display(); } } class QiuXie extends Clothes { function Display() { echo 球鞋 ; parent::Display(); } } class Tshirt extends Clothes { function Display() { echo T恤 ; parent::Display(); } } class Waitao extends Clothes { function Display() { echo 外套 ; parent::Display(); } }
header(Content-Type:text/html;charset=utf-8); //------------------------装饰器模式测试代码------------------ require_once ./Decorator/Decorator.php; $Yaoming=new Person(姚明); $aTai=new Person(A泰斯特); $pixie=new PiXie(); $waitao=new Waitao(); $pixie->Decorate($Yaoming); $waitao->Decorate($pixie); $waitao->Display(); echo
1. It is necessary to dynamically add functions to an object, and these functions can be dynamically revoked.
2. A very large number of functions generated by the permutation and combination of some basic functions need to be added, making the inheritance relationship unrealistic.
3. When the method of generating subclasses cannot be used for expansion. In one case, there may be a large number of independent extensions, and a large number of subclasses will be generated to support each combination, causing the number of subclasses to explode. Another case could be because the class definition is hidden, or the class definition cannot be used to generate subclasses.