PHP design pattern: code example of the modifier pattern, and php design pattern. PHP design pattern: Decorator pattern code example. php design pattern definition: The Decorator pattern dynamically extends the class features without modifying the original class code and inheritance. Traditional programming model PHP design mode: code example of the modifier mode, php design mode
Definition:
The modifier mode dynamically extends the class functions without modifying the original class code and inheritance. The traditional programming mode is that subclass inherits the parent class implementation method overload. with the decorator mode, you only need to add a new decorator object, which is more flexible and avoids too many classes and layers.
Role:
Component (base class of the decorated object)
ConcreteComponent (specific object to be decorated)
Decorator)
ContreteDecorator (specific modifier class)
Sample code:
// Decorator base class interface Component {public function operation ();} // Decorator base class abstract class Decorator implements Component {protected $ component; public function _ construct (Component $ component) {$ this-> component = $ component;} public function operation () {$ this-> component-> operation ();}} // the modifier class ConcreteComponent implements Component {public function operation () {echo 'do operation '. PHP_EOL ;}}// specific decoration class Aclass ConcreteDecoratorA extends Decorator {public function _ construct (Component $ component) {parent ::__ construct ($ component);} public function operation () {parent: operation (); $ this-> addedOperationA (); // Newly added Operation} public function addedOperationA () {echo 'add operation '. PHP_EOL ;}}// the 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 ConcreteDecoratorA (new ConcreteComponent ()); $ decoratorA-> operation ();/* do operation Add Operation A Add Operation B */$ decoratorB = new ConcreteDecoratorB ($ decoratorA); $ decoratorB-> operation ();}} client: main ();
Definition: the modifier mode dynamically extends the functions of a class without modifying the original class code and inheritance. Traditional programming model...