C++设计模式之-外观模式

意图:

       为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一系统更加容易使用。

适用性:

       1、在设计初期阶段,应该要有意识的将不同的两个层分离,比如经典的三层架构,就需要考虑在数据访问层和业务逻辑层、业务逻辑层和表示层的层与层之间建立外观。

       2、在开发阶段,子系统往往因为不断的重构演化而变得越来越复杂,大多数模式使用时也都会产生很多很小的类,这本是好事,但也给外部调用他们的用户程序带来了使用上的困难,用外观模式提供一个简单的接口,减少他们之间的依赖。

       3、在维护一个遗留的大型系统时,可能这个系统已经非常难以维护和扩展了,但因为它包含非常重要的功能,新的需求开发必须要依赖于它。此时为新系统开发一个外观类,来提供设计粗糙或高度复杂的遗留代码的比较清晰简单的接口,让新系统与外观对象交互,外观对象与遗留代码交互所有复杂的工作。

代码实现:

 1 // Facade.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include<iostream>
 6 #include <string>
 7 using namespace std;
 8 
 9 class SubSystemOne
10 {
11 public:
12     void MethodOne()
13     {
14         cout<<"子系统方法一"<<endl;
15     }
16 };
17 
18 class SubSystemTwo
19 {
20 public:
21     void MethodTwo()
22     {
23         cout<<"子系统方法二"<<endl;
24     }
25 };
26 
27 class SubSystemThree
28 {
29 public:
30     void MethodThree()
31     {
32         cout<<"子系统方法三"<<endl;
33     }
34 };
35 
36 class SubSystemFour
37 {
38 public:
39     void MethodFour()
40     {
41         cout<<"子系统方法四"<<endl;
42     }
43 };
44 
45 class Facade
46 {
47 private:
48     SubSystemOne *one;
49     SubSystemTwo *two;
50     SubSystemThree *three;
51     SubSystemFour *four;
52 public:
53     void MethodA()
54     {
55         cout<<"方法A组:"<<endl;
56         one->MethodOne();
57         two->MethodTwo();
58         four->MethodFour();
59     }
60     void MethodB()
61     {
62         cout<<"方法B组:"<<endl;
63         two->MethodTwo();
64         three->MethodThree();
65     }
66 
67 };
68 
69 int _tmain(int argc, _TCHAR* argv[])
70 {
71     Facade *fade = new Facade();
72     fade->MethodA();
73     fade->MethodB();
74     system("pause");
75     return 0;
76 }

具体实现参考程洁的《大话设计模式》

猜你喜欢

转载自www.cnblogs.com/wxmwanggood/p/9275060.html