外观模式
外观模式定义
外观模式(Façade),为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
外观模式结构图
外观模式结构图如下所示:

图 01 外观模式结构图
外观模式套用代码
1 #include "iostream" 2 using namespace std; 3 class SubSystemOne 4 { 5 public: 6 void MethodOne() 7 { 8 cout << "MethodOne" << endl; 9 } 10 }; 11 12 class SubSystemTwo 13 { 14 public: 15 void MethodTwo() 16 { 17 cout << "MethodTwo" << endl; 18 } 19 }; 20 21 22 class SubSystemThree 23 { 24 public: 25 void MethodThree() 26 { 27 cout << "MethodThree" << endl; 28 } 29 }; 30 31 32 class SubSystemFour 33 { 34 public: 35 void MethodFour() 36 { 37 cout << "MethodFour" << endl; 38 } 39 }; 40 41 // 外观类 42 class Facade 43 { 44 private: 45 SubSystemOne* one; 46 SubSystemTwo* two; 47 SubSystemThree* three; 48 SubSystemFour* four; 49 public: 50 Facade() 51 { 52 one = new SubSystemOne(); 53 two = new SubSystemTwo(); 54 three = new SubSystemThree(); 55 four = new SubSystemFour(); 56 } 57 58 // 根据不同的方法组调用不同的子系统 59 void MethodA() 60 { 61 cout << "MethodA" << endl; 62 one->MethodOne(); 63 two->MethodTwo(); 64 four->MethodFour(); 65 } 66 67 void MethodB() 68 { 69 cout << "MethodB" << endl; 70 one->MethodOne(); 71 three->MethodThree(); 72 four->MethodFour(); 73 } 74 }; 75 76 void main() 77 { 78 Facade facade; 79 facade.MethodA(); 80 facade.MethodB(); 81 }
外观模式实例应用
外观模式实例应用类图

图 02 外观模式实例应用类图
外观模式实例应用代码
以下的代码仅仅是为了理解这个模式,并没有进行更深层次的优化。
1 #include "iostream" 2 using namespace std; 3 4 // ¹ÉƱÀà 5 class CStock 6 { 7 public: 8 void Sell() 9 { 10 cout << "sell stock" << endl; 11 } 12 13 void Buy() 14 { 15 cout << "buy stock" << endl; 16 } 17 }; 18 19 // ¹úÕ®Àà 20 class CNationalDebt 21 { 22 public: 23 void Sell() 24 { 25 cout << "sell CNationalDebt" << endl; 26 } 27 28 void Buy() 29 { 30 cout << "buy CNationalDebt" << endl; 31 } 32 }; 33 34 // ·¿µØ²úÀà 35 class CRealty 36 { 37 public: 38 void Sell() 39 { 40 cout << "sell CRealty" << endl; 41 } 42 43 void Buy() 44 { 45 cout << "buy CRealty" << endl; 46 } 47 }; 48 49 // »ù½ðÀà 50 class CFund 51 { 52 private: 53 CStock* stock; 54 CNationalDebt* debt; 55 CRealty* realty; 56 57 public: 58 CFund() 59 { 60 stock = new CStock(); 61 debt = new CNationalDebt(); 62 realty = new CRealty(); 63 } 64 65 void Sell() 66 { 67 stock->Sell(); 68 debt->Sell(); 69 realty->Sell(); 70 } 71 72 void Buy() 73 { 74 stock->Buy(); 75 debt->Buy(); 76 realty->Buy(); 77 } 78 }; 79 80 void main() 81 { 82 CFund* fund = new CFund(); 83 fund->Buy(); 84 fund->Sell(); 85 }
2014-11-29 10:49:27
浙公网安备 33010602011771号