1. 程式人生 > >《大話設計模式》c++實現 外觀模式

《大話設計模式》c++實現 外觀模式

外觀模式:為子系統中的一組介面提供一個一致的介面,此模式定義了一個高層介面,這個介面使得這一子系統更加容易使用。

 

 

 

 

外觀模式在什麼時候使用呢?

分為三個階段:

(1)首先,在設計初期階段,應該要有意識的將不同的兩個層分離。

(2)第二,在開發階段,子系統往往因為不斷的重構演化而變得越來越複雜,大多數的模式使用時也會產生很多很小的類,這本是好事兒,但是也給外部呼叫他們的使用者程式帶來了使用上的困難,增加外觀Facade可以提供一個簡單的介面,減少他們之間的依賴。

(3)第三,在維護一個遺留的大型系統時,可能這個系統已經非常難以維護和擴充套件了,但因為它包含非常重要的功能,新的需求開發必須要依賴於它。此時用外觀模式Facade也是非常合適的。

 

 1 #include<iostream>
 2 #include<string>
 3 
 4 class SubSystemOne{
 5 public:
 6     void MethodOne(){
 7         std::cout << "SubSystemOne MethodOne  " << std::endl;
 8     }
 9 };
10 
11 class SubSystemTwo{
12 public:
13     void MethodTwo(){
14         std::cout << "
SubSystemTwo MethodTwo " << std::endl; 15 } 16 }; 17 18 class SubSystemThree{ 19 public: 20 void MethodThree(){ 21 std::cout << "SubSystemThree MethodThree " << std::endl; 22 } 23 }; 24 25 class SubSystemFour{ 26 public: 27 void MethodFour(){ 28 std::cout << "
SubSystemFour MethodFour " << std::endl; 29 } 30 }; 31 32 33 class Facade{ 34 private: 35 SubSystemOne* one; 36 SubSystemTwo* two; 37 SubSystemThree* three; 38 SubSystemFour* four; 39 public: 40 Facade(){ 41 one = new SubSystemOne(); 42 two = new SubSystemTwo(); 43 three = new SubSystemThree(); 44 four = new SubSystemFour(); 45 46 } 47 ~Facade(){ 48 delete one; 49 delete two; 50 delete three; 51 delete four; 52 } 53 void MethodA(){ 54 std::cout << "MethodA-------" << std::endl; 55 one->MethodOne(); 56 two->MethodTwo(); 57 four->MethodFour(); 58 std::cout << std::endl; 59 } 60 void MethodB(){ 61 std::cout << "MethodB-------" << std::endl; 62 two->MethodTwo(); 63 three->MethodThree(); 64 std::cout << std::endl; 65 } 66 67 }; 68 69 70 71 72 73 //Client 74 void main() 75 { 76 Facade* facade = new Facade(); 77 78 facade->MethodA(); 79 facade->MethodB(); 80 81 delete facade; 82 83 system("pause"); 84 85 }