外觀模式是一種結(jié)構(gòu)型模式,它為子系統(tǒng)中的一組接口提供一個一致的界面,外觀模式定義了一個高層次的接口,使得子系統(tǒng)更加容易使用。
主要角色
外觀(Facade)角色
- 此角色將被客戶端調(diào)用
- 知道哪些子系統(tǒng)負(fù)責(zé)處理請求
- 將用戶的請求指派給適當(dāng)?shù)淖酉到y(tǒng)
子系統(tǒng)(subsystem)角色
- 實現(xiàn)子系統(tǒng)的功能
- 處理由Facade對象指派的任務(wù)
- 沒有Facade的相關(guān)信息,可以被客戶端直接調(diào)用
- 可以同時有一個或多個子系統(tǒng),每個子系統(tǒng)都不是一個單獨的類,而一個類的集合。每個子系統(tǒng)都可以被客戶端直接調(diào)用,或者被外觀角色調(diào)用。子系統(tǒng)并知道外觀模式的存在,對于子系統(tǒng)而言,外觀僅僅是另一個客戶端。
適用性
- 為一些復(fù)雜的子系統(tǒng)提供一組接口
- 提高子系統(tǒng)的獨立性
- 在層次化結(jié)構(gòu)中,可以使用外觀模式定義系統(tǒng)的每一層的接口
優(yōu)點
- 它對客戶屏蔽了子系統(tǒng)組件,因而減少了客戶處理的對象的數(shù)目并使得子系統(tǒng)使用起來更加方便
- 實現(xiàn)了子系統(tǒng)與客戶之間的松耦合關(guān)系
- 如果應(yīng)用需要,它并不限制它們使用子系統(tǒng)類。因此可以在系統(tǒng)易用性與能用性之間加以選擇
類圖
實例
class HomeTheaterFacade
{
private $amp;
private $tuner;
private $dvd;
private $projector;
private $screen;
private $popper;
public function __construct(Amplifier $amp, Tuner $tuner, DvdPlayer $dvd, Projector $projector, Screen $screen, PopcornPopper $popper)
{
$this->amp = $amp;
$this->tuner = $tuner;
$this->dvd = $dvd;
$this->projector = $projector;
$this->screen = $screen;
$this->popper = $popper;
}
public funtion watchMoive()
{
$this->pop->on();
$this->pop->pop();
$this->screen->down();
$this->projector->on();
$this->projector->wideScreenMode();
$this->amp->on();
$this->amp->setDvd($dvd);
$this->dvd->on();
$this->dvd->play();
}
public function endMoive()
{
...
}
}