Introduction to the policy pattern of PHP design pattern
Policy mode: defines algorithm families, which are encapsulated separately so that they can be replaced with each other. This mode allows algorithm changes to be independent of algorithm customers.
Encapsulation: encapsulate behavior with interfaces. we can extract frequently changed parts from the current class and encapsulate them separately using interfaces.
Replace each other: we have encapsulated interfaces and implemented classes to change algorithms by specifying different interfaces.
Mind Map
class Duck{ private $_flyBehavior; public function performFly(){ $this->_flyBehavior->fly(); } public function setFlyBehavior(FlyBehavior $behavior){ $this->_flyBehavior = $behavior; }}class RubberDuck extends Duck{}// Test Case $ duck = new RubberDuck ();/* fly the duck with wings */$ duck-> setFlyBehavior (new FlyWithWings ()); $ duck-> mongomfly ();/* fly the duck without wings */$ duck-> setFlyBehavior (new FlyWithNo (); $ duck-> mongomfly ();
Summary
In general, our design principles in development are as follows:
1. identify potential changes in the application and separate them from those that do not need to be changed;
2. interface programming, not implementation programming;
3. multi-purpose combination and less inheritance;
References: head first design model