一、UML圖
關鍵詞:增加Facade層。
二、概念
外觀模式:爲子系統中的一組接口提供一個一致的界面,此模式定義了一個高層接口,這個接口使得這一子系統更加容易使用。
三、說明
Q:外觀模式在什麼時候使用呢?
A:分爲三個階段:
(1)首先,在設計初期階段,應該要有意識的將不同的兩個層分離。
(2)第二,在開發階段,子系統往往因爲不斷的重構演化而變得越來越複雜,大多數的模式使用時也會產生很多很小的類,這本是好事兒,但是也給外部調用他們的用戶程序帶來了使用上的困難,增加外觀Facade可以提供一個簡單的接口,減少他們之間的依賴。
(3)第三,在維護一個遺留的大型系統時,可能這個系統已經非常難以維護和擴展了,但因爲它包含非常重要的功能,新的需求開發必須要依賴於它。此時用外觀模式Facade也是非常合適的。
具體而言:爲新系統開發一個外觀Facade類,來提供設計粗糙或高度複雜的遺留代碼的比較清晰簡單的接口,讓新系統與Facade對象交互,Facade與遺留代碼交互所有複雜的工作。
好處是顯而易見的,如下圖所示:
四、C++實現
(1)Facade.h
#ifndef FACADE_H
#define FACADE_H
#include <iostream>
#include <string>
//SubSystem Class,實現子系統的功能,處理Facade對象指派的任務。注意子類中沒有Facade任何信息,即沒有對Facade對象的引用。
//下面是四個子系統的類
class SubSystemOne
{
public:
void MethodOne()
{
std::cout<<"子系統方法一"<<std::endl;
}
};
class SubSystemTwo
{
public:
void MethodTwo()
{
std::cout<<"子系統方法二"<<std::endl;
}
};
class SubSystemThree
{
public:
void MethodThree()
{
std::cout<<"子系統方法三"<<std::endl;
}
};
class SubSystemFour
{
public:
void MethodFour()
{
std::cout<<"子系統方法四"<<std::endl;
}
};
//Facade Class,外觀類,知道有哪些子系統類,負責處理請求,將客戶的請求代理給適當的子系統對象。
class Facade
{
private:
SubSystemOne* one;
SubSystemTwo* two;
SubSystemThree* three;
SubSystemFour* four;
public:
Facade()
{
one=new SubSystemOne();
two=new SubSystemTwo();
three=new SubSystemThree();
four=new SubSystemFour();
}
~Facade()
{
delete one;
delete two;
delete three;
delete four;
}
void MethodA()
{
std::cout<<"方法組A()------"<<std::endl;
one->MethodOne();
two->MethodTwo();
four->MethodFour();
std::cout<<std::endl;
}
void MethodB()
{
std::cout<<"方法組B()------"<<std::endl;
two->MethodTwo();
three->MethodThree();
std::cout<<std::endl;
}
};
#endif
(2)Client.cpp
#include "Facade.h"
#include <iostream>
#include <cstdlib>
//Client
void main()
{
Facade* facade=new Facade();
facade->MethodA();
facade->MethodB();
delete facade;
system("pause");
}
(3)運行結果