外观模式:为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
四个子系统类
class SubSystemOne
{
public:
void MethodOne()
{
cout <<"SystemOne" << endl;
}
};
class SubSystemTwo
{
public:
void MethodTwo()
{
cout <<"SystemTwo" << endl;
}
};
class SubSystemThree
{
public:
void MethodThree()
{
cout <<"SystemThree" << endl;
}
};
class SubSystemFour
{
public:
void MethodFour()
{
cout <<"SystemFour" << endl;
}
};
外观类
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;
}
void MethodA()
{
one->MethodOne();
two->MethodTwo();
four->MethodFour();
}
void MehtodB()
{
two->MethodTwo();
three->MethodThree();
}
};
客户端调用
void main()
{
Facade *facade = new Facade;
facade->MethodA();
facade->MethodB();
}
适用:
1.在设计初期阶段,应该要有意识的将不同的两个层分离,比如经典的三层构架,就需要考虑在数据访问层和业务逻辑层、业务逻辑层和表示层的层与层之间建立外观Facade,这样可以为复杂的子系统提供一个简单的接口,使得耦合大大降低。
2.在开发阶段,子系统往往因为不断的重构演化而变得越来越复杂,大多数的模式使用时也都会产生很多很小的类,这本是好事,但是也给外部调用他们的用户程序带来了使用上的困难,增加外观Facade可以提供一个简单地接口,减少他们之间的依赖。
3.在维护一个遗留的大型系统时,可能这个系统已经非常难以维护和扩展了,但因为它包含非常重要的功能,新的需求开发必须要依赖与它。此时用外观模式Facade也是非常合适的。你可以为新系统开发一个外观Facade类,来提供设计粗糙或高度复杂的遗留代码的比较清晰简单地接口,让新系统与Facade对象交互,Facade与遗留代码交互所有复杂的工作。