最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
php设计模式的策略,适配器和观察者模式介绍
时间:2022-10-18 编辑:坚强 来源:一聚教程网
本文为小伙伴们带来了关于php设计模式的策略,适配器和观察者模式介绍的相关内容,感兴趣的小伙伴一起来看看吧。
策略模式
特点
定义一系列算法封装起来, 让他们可以相互替代,策略模式提供了管理相关算法族的办法, 提供了可以体会继承关系的棒法, 避免使用多重条件转移语句
实现
_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);
观察者模式
特点
当一个对象状态发生变化时, 依赖他的对象全部收到通知, 并主动更新。观察者模式实现了低耦合, 非侵入式的通知与更新机制。
实现
_observers[] = $observer; } public function notify() { foreach($this->_observers as $object) { $object->watch(); } } } // 观察者 class Cat1 implements Observer{ public function watch(){ echo "Cat1 watches TV
"; } } class Dog1 implements Observer{ public function watch(){ echo "Dog1 watches TV
"; } } class People implements Observer{ public function watch(){ echo "People watches TV
"; } } $action = new WatchAction(); $action->register(new Cat1()); $action->register(new People()); $action->register(new Dog1()); $action->notify();
总结
以上就是关于php设计模式的策略,适配器和观察者模式介绍的全部内容了,感兴趣的小伙伴记得点击关注哦。
-
上一个: PHP实现动态表单生成工具教程
-
下一个: PHP数组的内部实现介绍
相关文章
- PHP导出数据超时的优化建议解读 10-31
- PHP之mysql位运算解析 10-31
- Laravel实现登录跳转功能解析 10-31
- php双向队列解读 10-31
- Laravel异常上下文解决教程 10-24
- php数组查询元素位置方法介绍 10-24