C++ 设计模式 外观模式 The Facade Pattern
介绍
Facade Pattern 为一组复杂的子系统提供了一个统一的简单接口,它是一种结构型设计模式。
它隐藏了子系统的复杂性,并向客户端提供了一个简单的接口来访问子系统。通过使用 Facade 模式,客户端可以方便地使用子系统,而不必了解子系统的内部细节。
Facade 模式由以下三个角色组成:
- Facade 类:它是一个Facade类,它定义了客户端可以使用的简单接口。
- Subsystem 类:它是一组复杂的子系统,它们完成了客户端请求的具体工作。
- Client 类:它是一个客户端类,它通过使用 Facade 类来请求子系统。
Facade 模式的优点包括:
- 减少了客户端和子系统的耦合。
- 提高了子系统的独立性。
- 提高了客户端的可用性。
- 提高了系统的整体容错性。
在 C++ 中,Facade 模式可以使用继承和组合的方式实现。Facade 类可以继承自 Subsystem 类,也可以包含一个 Subsystem 类的对象。在 C++ 中,Facade 模式常常用于提供简单的接口来访问一组复杂的系统,从而简化客户端代码。
示例
#include <iostream>
// Subsystem class
class SubsystemA
{
public:
void operationA()
{
std::cout << "Subsystem A operation" << std::endl;
}
};
class SubsystemB
{
public:
void operationB()
{
std::cout << "Subsystem B operation" << std::endl;
}
};
// Facade class
class Facade
{
private:
SubsystemA *subA;
SubsystemB *subB;
public:
Facade()
{
subA = new SubsystemA();
subB = new SubsystemB();
}
void operation()
{
std::cout << "Facade operation starts" << std::endl;
subA->operationA();
subB->operationB();
std::cout << "Facade operation ends" << std::endl;
}
};
// Client class
int main()
{
Facade *facade = new Facade();
facade->operation();
return 0;
}
维基百科示例
C++ Programming: Code patterns design - Wikibooks, open books for an open world
/*Facade is one of the easiest patterns I think... And this is very simple example.
Imagine you set up a smart house where everything is on remote. So to turn the lights on you push lights on button - And same for TV,
AC, Alarm, Music, etc...
When you leave a house you would need to push a 100 buttons to make sure everything is off and are good to go which could be little
annoying if you are lazy like me
so I defined a Facade for leaving and coming back. (Facade functions represent buttons...) So when I come and leave I just make one
call and it takes care of everything...
*/
#include <string>
#include <iostream>
using namespace std;
class Alarm
{
public:
void alarmOn()
{
cout << "Alarm is on and house is secured"<<endl;
}
void alarmOff()
{
cout << "Alarm is off and you can go into the house"<<endl;
}
};
class Ac
{
public:
void acOn()
{
cout << "Ac is on"<<endl;
}
void acOff()
{
cout << "AC is off"<<endl;
}
};
class Tv
{
public:
void tvOn()
{
cout << "Tv is on"<<endl;
}
void tvOff()
{
cout << "TV is off"<<endl;
}
};
class HouseFacade
{
Alarm alarm;
Ac ac;
Tv tv;
public:
HouseFacade(){}
void goToWork()
{
ac.acOff();
tv.tvOff();
alarm.alarmOn();
}
void comeHome()
{
alarm.alarmOff();
ac.acOn();
tv.tvOn();
}
};
int main()
{
HouseFacade hf;
//Rather than calling 100 different on and off functions thanks to facade I only have 2 functions...
hf.goToWork();
hf.comeHome();
}
优缺点
Facade 模式的优缺点:
优点:
- 可以隐藏代码的复杂度,对客户端友好。
- 降低了错误使用的可能性。
- 可以方便地将复杂系统移植到其他平台,因为客户端只依赖于Facade。
缺点:
- Facade可能承担太多的责任,最终变成 God Object 这种反设计模式。
God object - Wikipedia