外观模式简介
外观模式(Facade),为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
在设计的初期阶段,应该要有意识将不同的两个层分离,比如经典的三层结构,就需要考虑在数据访问层和业务逻辑层、业务逻辑层和表示层的层与层之间建立外观模式,这样可以为复杂的子系统提供一个简单的接口,使得耦合大大降低。其次在开发阶段,子系统往往因为不断的重构演化而变得越来越复杂,大多数的模式使用时也都会产生很多的小类,这本是好事,但也给外部的调用他们的用户程序带来使用上的困难,增加外观(Facade)可以提供一个简单的接口,减少他们之间的依赖。第三,在维护一个遗留的大型项目时,可能这个系统已经非常难以维护和扩展了,但因为它包含非常重要的功能,新的需求必须要依赖与它,此时用外观模式也是非常合适的,你可以为一个新系统开发一个外观类,来提供实际粗糙或高度复杂的遗留代码的比较清晰的简单的接口,让新系统与外观类对象交互,外观类与遗留代码交互所有复杂的工作。
其实我的理解是,外观只是对一部分有相互联系的类的整合,把他们的方法整合在一起,根据用户程序的调用习惯提供一个统一的对外的接口,方便外界调用。
外观模式UML类图
C++代码实现
// 要被整合方法的Subsystem1类 #ifndef _SUBSYSTEM1_HPP #define _SUBSYSTEM1_HPP #include<iostream> using namespace std; class Subsystem1{ public: void method1(){ cout << "Subsystem1.method1() is called" <<endl; } void method2(){ cout << "Subsystem1.method2() is called" << endl; } }; #endif
//要被整合方法的Subsystem2类 #ifndef _SUBSYSTEM2_HPP #define _SUBSYSTEM2_HPP #include<iostream> using namespace std; class Subsystem2{ public: void method1(){ cout << "Subsystem2.method1() is called" <<endl; } void method2(){ cout << "Subsystem2.method2() is called" << endl; } }; #endif
//要被整合方法的Subsystem3类 #ifndef _SUBSYSTEM3_HPP #define _SUBSYSTEM3_HPP #include<iostream> using namespace std; class Subsystem3{ public: void method1(){ cout << "Subsystem3.method1() is called" <<endl; } void method2(){ cout << "Subsystem3.method2() is called" << endl; } }; #endif
//外观类,根据用户需求更合方法 #ifndef _SUBSYSTEM3_HPP #define _SUBSYSTEM3_HPP #include<iostream> using namespace std; class Subsystem3{ public: void method1(){ cout << "Subsystem3.method1() is called" <<endl; } void method2(){ cout << "Subsystem3.method2() is called" << endl; } }; #endif
// 用户程序 #include"facade.hpp" int main(){ Facade fa; fa.methodOne(); fa.methodTwo(); getchar(); return 0; }