第十二章-外观模式

外观模式(Facade): 为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
它完美的体现了依赖倒转原则和迪米特法则的思想

图片

基本代码

#include<iostream>
#include<string>

using namespace std;

class SubSystemOne
{
public:
	void MethodOne()
	{
		cout << "子系统方法一" << endl;
	}
};

class SubSystemTwo
{
public:
	void MethodTwo()
	{
		cout << "子系统方法二" << endl;
	}
};

class SubSystemThree
{
public:
	void MethodThree()
	{
		cout << "子系统方法三" << endl;
	}
};

class SubSystemFour
{
public:
	void MethodFour()
	{
		cout << "子系统方法四" << 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()
	{
		cout << "方法组A()----- " << endl;
		one->MethodOne();
		two->MethodTwo();
		four->MethodFour();
	}

	void MethodB()
	{
		cout << "方法组B()----- " << endl;
		two->MethodTwo();
		four->MethodFour();
	}
};

int main()
{
	Facade *facade = new Facade();  //由于Facade的作用,客户端可以根本不知道三个子系统类的存在

	facade->MethodA();
	facade->MethodB();

	system("pause");
	return 0;
}

何时使用外观模式

  • 首先,在设计初期阶段,应该要有意识的将不同的两个层分离,比如经典的三层架构,就需要考虑在数据访问层和业务逻辑层,业务逻辑层和表示层的层与层之间建立外观Facade,这样可以为复杂的子系统提供一个简单的接口,使得耦合大大降低。
  • 其次,在开发阶段,子系统往往因为不断地重构演化而变得越来越复杂,增加外观Facade可以提供一个简单的接口,减少他们之间的依赖。
  • 第三,在维护一个遗留的大型系统时,可能这个系统已经很难维护和扩展了,可以为新系统开发一个外观Facade类,来提供设计粗糙或高度复杂的遗留代码的比较清晰简单的接口,让新系统与Facade对象交互,Facade与遗留代码交互所有复杂的工作。

图片

原文地址:https://www.cnblogs.com/wfcg165/p/12004763.html