|
定義:外觀模式(Facade):又叫門面模式,為子系統(tǒng)中的一組接口提供一個(gè)一致的界面,此模式定義了一個(gè)高層接口,這個(gè)接口使得這一子系統(tǒng)更加容易使用。 代碼實(shí)例:假設(shè)實(shí)現(xiàn)一個(gè)功能需要用到子系統(tǒng)中的四個(gè)方法。 /** * Class SubSystemOne */ class SubSystemOne { public function methodOne() { return '子系統(tǒng)方法一' . '<br>'; } } /** * Class SubSystemTwo */ class SubSystemTwo { public function methodTwo() { return '子系統(tǒng)方法二' . '<br>'; } } /** * Class SubSystemThree */ class SubSystemThree { public function methodThree() { return '子系統(tǒng)方法三' . '<br>'; } } /** * Class SubSystemFour */ class SubSystemFour { public function methodFour() { return '子系統(tǒng)方法四' . '<br>'; } } 如果不使用外觀模式,客戶端代碼應(yīng)該為: $subSystemOne = new SubSystemOne(); $subSystemTwo = new SubSystemTwo(); $subSystemThree = new SubSystemThree(); $subSystemFour = new SubSystemFour(); echo $subSystemOne->methodOne(); echo $subSystemTwo->methodTwo(); echo $subSystemThree->methodThree(); echo $subSystemFour->methodFour(); 這樣的寫法需要客戶端了解子系統(tǒng)的具體實(shí)現(xiàn)方法,且代碼沒有解耦,如果子系統(tǒng)發(fā)生變化,則所有的客戶端調(diào)用都需要進(jìn)行相應(yīng)的變化。
以下使用外觀模式: /** * 外觀類,整合需要調(diào)用的子系統(tǒng)代碼,給客戶端調(diào)用,如果子系統(tǒng)發(fā)生變化,只用修改外觀類代碼 * Class Facade */ class Facade { /** * @var */ private $subSystemOne; /** * @var */ private $subSystemTwo; /** * @var */ private $subSystemThree; /** * @var */ private $subSystemFour; /** * Facade constructor. */ public function __construct() { $this->subSystemOne = new SubSystemOne(); $this->subSystemTwo = new SubSystemTwo(); $this->subSystemThree = new SubSystemThree(); $this->subSystemFour = new SubSystemFour(); } /** * 整合方法 */ public function method() { echo $this->subSystemOne->methodOne(); echo $this->subSystemTwo->methodTwo(); echo $this->subSystemThree->methodThree(); echo $this->subSystemFour->methodFour(); } } 客戶端調(diào)用: $facade = new Facade(); // 客戶端可以不用知道子系統(tǒng)的存在,調(diào)用外觀類中提供的方法就可以 $facade->method(); 結(jié)果: 子系統(tǒng)方法一
子系統(tǒng)方法二
子系統(tǒng)方法三
子系統(tǒng)方法四
總結(jié):
|
|
|