Facade(外观)模式

  外观模式是类结构型设计模式之一,描述的是一组具有类似功能的类群。

案例:输入系统中有多个输入子系统:键盘、触摸屏、鼠标等,它们都要为上层应用程序提供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;
}

  编译运行,和前面的一致:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值