外观模式是类结构型设计模式之一,描述的是一组具有类似功能的类群。
案例:输入系统中有多个输入子系统:键盘、触摸屏、鼠标等,它们都要为上层应用程序提供x、y坐标。
若用户代码直接操作这些输入子系统:
class SubMouse
{
public:
void get_mouse_location() { cout << "Mouse:\tx = 240, y = 660" << endl; }
};
class SubTouch
{
public:
void get_touch_location() { cout << "Touch:\tx = 445, y = 636" << endl; }
};
class SubKey
{
public:
void get_key_location() { cout << "Key:\tx = 635, y = 754" << endl; }
};
int main(void)
{
SubMouse* mouse = new SubMouse;
SubTouch* touch = new SubTouch;
SubKey* key = new SubKey;
mouse->get_mouse_location();
touch->get_touch_location();
key->get_key_location();
delete mouse;
delete touch;
delete key;
return 0;
}
显然,用户代码和输入子系统的耦合性太强,为使它们解耦合,引入了上述的外观模式,使得子系统统一接口,让子系统更加容易调用。
UML图:
Facade:为用户代码调用简单而定义的调用接口;
SubSystem*:功能的类群(模块或子系统),即功能提供者。
class SubMouse
{
public:
void get_mouse_location() { cout << "Mouse:\tx = 240, y = 660" << endl; }
};
class SubTouch
{
public:
void get_touch_location() { cout << "Touch:\tx = 445, y = 636" << endl; }
};
class SubKey
{
public:
void get_key_location() { cout << "Key:\tx = 635, y = 754" << endl; }
};
int main(void)
{
SubMouse* mouse = new SubMouse;
SubTouch* touch = new SubTouch;
SubKey* key = new SubKey;
mouse->get_mouse_location();
touch->get_touch_location();
key->get_key_location();
delete mouse;
delete touch;
delete key;
return 0;
}
编译运行,和前面的一致: