标签:硬编码 解耦 public cte nim const bsp dog protect
// 策略的接口定义策略的所有行为 interface Animal { public function run(); public function eat(); } // 实现接口的所有方法 class Cat implements Animal { public function run() { echo "cat run"; } public function eat() { echo "cat eat"; } } // 实现接口的所有方法 class Dog implements Animal { public function run() { echo "dog run"; } public function eat() { echo "dog eat"; } } class MyAnimal { protected $animal; public function __construct(Animal $animal) { $this->animal = $animal; } public function get() { $this->animal->run(); $this->animal->eat(); } } $MyAnimal = new MyAnimal(new Cat()); $MyAnimal->get(); $MyAnimal = new MyAnimal(new Dog()); $MyAnimal->get();
策略模式实现了硬编码到解耦。
标签:硬编码 解耦 public cte nim const bsp dog protect
原文地址:https://www.cnblogs.com/licnlt/p/9714804.html