大话设计模式
1 外观模式(Facade)结构图
2 对该模式的一些解释
2.1 概念:为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
2.2 使用场景
- 首先,在设计初期阶段,应该要有意识的将不同的两个层分离。
- 第二,在开发阶段,子系统往往因为不断的重构演化而变得越来越复杂,大多数的模式使用时也会产生很多很小的类,这本是好事儿,但是也给外部调用他们的用户程序带来了使用上的困难,增加外观Facade可以提供一个简单的接口,减少他们之间的依赖。
- 第三,在维护一个遗留的大型系统时,可能这个系统已经非常难以维护和扩展了,但因为它包含非常重要的功能,新的需求开发必须要依赖于它。此时用外观模式Facade也是非常合适的。为新系统开发一个外观Facade类,来提供设计粗糙或高度复杂的遗留代码的比较清晰简单的接口,让新系统与Facade对象交互,Facade与遗留代码交互所有复杂的工作。如下图所示:
2.3 外观模式,其实质就是对类的包装,它完美的体现了依赖倒转原则和迪米特法则的思想。
2.4 外观模式代码
四个子系统的类:
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();
}
~Facade()
{
delete one;
delete two;
delete three;
delete four;
}
void MethodA()
{
one->MethodOne();
two->MethodTwo();
}
void MethodB()
{
three->MethodThree();
four->MethodFour();
}
};
客户端:
int main()
{
Facade *facade = new Facade();
facade->MethodA();
facade->MethodB();
return 0;
}
三 C++代码实现
3.1 代码结构图:
3.2 C++代码
#include<iostream>
#include<string>
using namespace std;
class Stock1
{
public:
void sell()
{
cout << "卖股票一" << endl;
}
void buy()
{
cout << "买股票一" << endl;
}
};
class Stock2
{
public:
void sell()
{
cout << "卖股票二" << endl;
}
void buy()
{
cout << "买股票二" << endl;
}
};
class NationalDebt
{
public:
void sell()
{
cout << "卖国债" << endl;
}
void buy()
{
cout << "买国债" << endl;
}
};
//外观类
class Fund
{
private:
Stock1 *stk1 = nullptr;
Stock2 *stk2 = nullptr;
NationalDebt *nade = nullptr;
public:
Fund()
{
stk1 = new Stock1();
stk2 = new Stock2();
nade = new NationalDebt();
}
~Fund()
{
delete stk1;
delete stk2;
delete nade;
}
void buyFund()
{
stk1->buy();
stk2->buy();
nade->buy();
}
void sellFund()
{
stk1->sell();
stk2->sell();
nade->sell();
}
};
//客户端
int main()
{
Fund *fund = new Fund();
fund->buyFund();
fund->sellFund();
if (fund)
{
delete fund;
fund = nullptr;
}
system("pause");
return 0;
}
买股票一
买股票二
买国债
卖股票一
卖股票二
卖国债
请按任意键继续. . .