PHP Design Pattern Decorator Pattern code example, PHP design mode
Defined:
Decorator mode is the ability to dynamically extend a class without modifying the original class code and inheritance. The traditional programming pattern is the subclass inherits the parent class implementation method overload, uses the adorner pattern, simply adds a new adorner object, is more flexible, avoids the class quantity and the hierarchy too much.
Role:
Component (base class for decorative objects)
Concretecomponent (specifically decorated objects)
Decorator (Decorator base class)
Contretedecorator (Specific decorator Class)
Example code:
The Decorator base class interface component{Public function operation ();}//Decorator base class abstract class Decorator implements component{protect Ed $component; Public function __construct (Component $component) {$this->component = $component; Public function operation () {$this->component->operation (); }}//Concrete decorator class Concretecomponent implements component{Public function operation () {echo ' do operation '. Php_eol; }}//Concrete decoration class AClass Concretedecoratora extends Decorator {public function __construct (Component $component) {parent::__ Construct ($component); } public Function operation () {parent::operation (); $this->addedoperationa (); New added action} public Function Addedoperationa () {echo ' Add Operation A '. Php_eol; }}//Concrete decoration class Bclass Concretedecoratorb extends Decorator {public function __construct (Component $component) {parent::__ Construct ($component); } public Function operation () {parent::operation (); $this->addedoperationb (); } PublIC function addedoperationb () {echo ' Add operation B '. Php_eol; }} class Client {public static function main () {/* Do operation ADD Operation A * * $decoratorA = new C Oncretedecoratora (New Concretecomponent ()); $decoratorA->operation (); /* Do operation add operation A Add Operation B */$decoratorB = new Concretedecoratorb ($decoratorA); $decoratorB->operation (); }} client::main ();
http://www.bkjia.com/PHPjc/997909.html www.bkjia.com true http://www.bkjia.com/PHPjc/997909.html techarticle PHP design pattern of the decorator pattern code example, PHP design pattern definition: Decorator mode is not to modify the original class code and inheritance in the case of dynamic extension of the function of the class. Traditional programming Model ...