特点
定义一系列算法封装起来, 让他们可以相互替代,策略模式提供了管理相关算法族的办法, 提供了可以体会继承关系的棒法, 避免使用多重条件转移语句
实现
<?phpabstract class Strategy{ abstract function goSchool();}class Run extends Strategy{ public function goSchool() { echo "走路去学校"; }}class Subway extends Strategy{ public function goSchool() { echo "地铁去学校"; }}class Bike extends Strategy{ public function goSchool() { echo "公交去学校"; }}class GoSchoolContext{ protected $_stratege; public function __construct($stratege) { $this->_stratege = $stratege; } public function goSchool() { $this->_stratege->goSchool(); }}$traget = new Run();$obj = new GoSchoolContext($traget);$obj->goSchool();
需要的东西在面前,但却不能用,而短时间又无法改造它,于是就想办法适配
// 适配器interface Charget{ public function putCharget();}class China implements Charget{ private $v = 220; public function putCharget() { return $this->v; }}class Adper extends China{ public function putCharget() { return parent::putCharget() / 2 + 10; }}class Phone{ public function charge(Charget $charge) { if ($charge->putCharget() != "120") { echo "不能充电"; } else { echo "能充电"; } }}$china = new China();$adper = new Adper();$phone = new Phone();$phone->charge($adper);
当一个对象状态发生变化时, 依赖他的对象全部收到通知, 并主动更新。观察者模式实现了低耦合, 非侵入式的通知与更新机制。
<?php// 主题接口interface Subject{ public function register(Observer $observer);}// 观察者接口interface Observer{ public function watch();}// 主题class WatchAction implements Subject{ public $_observers = []; public function register(\Observer $observer) { $this->_observers[] = $observer; } public function notify() { foreach($this->_observers as $object) { $object->watch(); } }}// 观察者class Cat1 implements Observer{ public function watch(){ echo "Cat1 watches TV<hr/>"; }}class Dog1 implements Observer{ public function watch(){ echo "Dog1 watches TV<hr/>"; }} class People implements Observer{ public function watch(){ echo "People watches TV<hr/>"; } }$action = new WatchAction();$action->register(new Cat1());$action->register(new People());$action->register(new Dog1());$action->notify();
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注w3xue的更多内容!
本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728