PHP設(shè)計(jì)模式的策略,適配器和觀察者模式詳解
策略模式
特點(diǎn)
定義一系列算法封裝起來, 讓他們可以相互替代,策略模式提供了管理相關(guān)算法族的辦法, 提供了可以體會(huì)繼承關(guān)系的棒法, 避免使用多重條件轉(zhuǎn)移語句
實(shí)現(xiàn)
<?php abstract class Strategy { abstract function goSchool(); } class Run extends Strategy { public function goSchool() { echo "走路去學(xué)校"; } } class Subway extends Strategy { public function goSchool() { echo "地鐵去學(xué)校"; } } class Bike extends Strategy { public function goSchool() { echo "公交去學(xué)校"; } } 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();
適配器模式
特點(diǎn)
需要的東西在面前,但卻不能用,而短時(shí)間又無法改造它,于是就想辦法適配
實(shí)現(xiàn)
// 適配器 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);
觀察者模式
特點(diǎn)
當(dāng)一個(gè)對(duì)象狀態(tài)發(fā)生變化時(shí), 依賴他的對(duì)象全部收到通知, 并主動(dòng)更新。觀察者模式實(shí)現(xiàn)了低耦合, 非侵入式的通知與更新機(jī)制。
實(shí)現(xiàn)
<?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();
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
利用swoole+redis實(shí)現(xiàn)股票和區(qū)塊鏈服務(wù)
這篇文章主要給大家介紹了關(guān)于利用swoole+redis實(shí)現(xiàn)股票和區(qū)塊鏈服務(wù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)下吧。2017-09-09PHP SPL標(biāo)準(zhǔn)庫中的常用函數(shù)介紹
這篇文章主要介紹了PHP SPL標(biāo)準(zhǔn)庫中的常用函數(shù)介紹,本文著重講解了spl_autoload_extensions()、spl_autoload_register()、spl_autoload()三個(gè)函數(shù),需要的朋友可以參考下2015-05-05PHP日期時(shí)間函數(shù)的高級(jí)應(yīng)用技巧
PHP的日期時(shí)間函數(shù)date()中介紹了PHP日期時(shí)間函數(shù)的簡(jiǎn)單用法,這類將介紹更多的函數(shù)來豐富我們的應(yīng)用。2009-05-05