: This article mainly introduces the HeadFirst-policy mode. if you are interested in the PHP Tutorial, refer to it. The policy mode defines the algorithm family and encapsulates them so that they can replace each other. this mode makes the algorithm changes independent of the customers who use the algorithm.
Next we will use ducks to explain the strategy model. Ducks have two kinds of behavior: they can scream and fly, but not all ducks can scream and fly, therefore, we can extract the changed behavior from the two.
flyBehavior->fly(); } public function performQuack(){ $this->quackBehavior->quack(); } public function setFlyBehavior(FlyBehavior $fb){ $this->flyBehavior = $fb; } public function setQuackBehavior(QuackBehavior $qb){ $this->quackBehavior = $qb; } public function swim(){ } abstract function display();}interface FlyBehavior{ public function fly();}class FlywithWings implements FlyBehavior{ public function fly(){ echo "i'm flying!\n"; }}class FlyNoWay implements FlyBehavior{ public function fly(){ echo "i can't fly.\n"; }}class FlyRocketPowered implements FlyBehavior{ public function fly(){ echo "i'm flying with a rocket!\n"; }}interface QuackBehavior{ public function quack();}class Quack implements QuackBehavior{ public function quack(){ echo "quack!\n"; }}class MuteQuack implements QuackBehavior{ public function quack(){ echo "silence\n"; }}class MallardDuck extends Duck{ public function __construct(){ $this->quackBehavior = new Quack(); $this->flyBehavior = new FlyNoWay(); } public function display(){ echo "i'm a real mallar duck\n"; } }$duck = new MallardDuck;$duck->performFly();$duck->setFlyBehavior(new FlyRocketPowered);$duck->performFly();?>
From the code above, we can see that we abstract the Ducks, and the flight behavior and the traffic are in the form of interfaces. the design principle is to combine multiple purposes, use less inheritance, and use the above method, relatively more flexible, not only can algorithms be encapsulated into classes, but also "dynamically change behavior at runtime", as long as the combined behavior object meets the correct interface standards.
The above introduces the Head First-policy mode, including some content, and hope to be helpful to friends who are interested in PHP tutorials.