This article mainly introduces the decorator pattern code examples of PHP design patterns. The decorator pattern does not modify the original class code and This article provides code examples for dynamically extending the functions of a class under inheritance. Friends who need it can refer to it
Definition:
The decorator pattern is the function of dynamically extending a class without modifying the original class code and inheritance. The traditional programming model is that subclasses inherit the parent class to implement method overloading. Using the decorator pattern, you only need to add a new decorator object, which is more flexible and avoids too many classes and layers.
Character:
Component (base class of decorated object)
ConcreteComponent (specific decorated object)
Decorator (decorator base class)
ContreteDecorator (specific decorator class)
Sample code:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
//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(); } }
//Concrete decorator class class ConcreteComponent implements Component { public function operation() { echo 'do operation'.PHP_EOL; } }
//Specific decoration class A class 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 A '.PHP_EOL; } }
//Specific decoration type B class 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(); |