Strategy pattern, what is strategy pattern, defines a family of algorithms and encapsulates them separately so that they can be replaced with each other. This Patterns allow the algorithm to change independently of the clients using it.
Let’s use ducks to explain the strategy pattern. Ducks have two behaviors: quacking and flying. However, not all ducks can quack and fly, so we extract these two behaviors that give changes.
<?php abstract class Duck{ public $flyBehavior; public $quackBehavior; public function __construct(){ } public function performFly(){ $this->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 above code, we can see that we have abstracted the duck, and the flight behavior and quacking driving are in the form of interfaces. The design principle is to use more combinations and less inheritance. Using the above writing method, it is relatively more flexible. Not only will Algorithms are encapsulated into classes and can "dynamically change behavior at runtime", as long as the combined behavior object meets the correct interface standard.