设计模式(八)——外观模式

根据迪米特法则,如果两个类不必彼此直接通信,那么这两个类就不应当发生直接的相互作用。
Facade模式也叫外观模式,是由GoF提出的23种设计模式中的一种。
Facade模式为一组具有类似功能的类群,比如类库,子系统等等,提供一个一
致的简单的界面。这个一致的简单的界面被称作facade。

Façade(外观角色):为调用方, 定义简单的调用接口。
SubSystem(子系统角色):功能提供者。指提供功能的类群(模块或子系
统)。

外观模式就是将复杂的⼦类系统抽象到同⼀个的接⼝进⾏管理
,外界只需要通过此接⼝与⼦类系统进⾏交互,⽽不必要直接与复杂的⼦类
系统进⾏交互

#include <iostream>

using namespace std;

class TV
{
public:
    virtual void turn_on()
    {
        cout << "电视打开" << endl;
    }
    virtual void turn_off()
    {
        cout << "电视关闭" << endl;
    }
};

class LED
{
public:
    virtual void turn_on()
    {
        cout << "电灯打开" << endl;
    }
    virtual void turn_off()
    {
        cout << "电灯关闭" << endl;
    }
};

class MusicPlayer
{
public:
    virtual void turn_on()
    {
        cout << "音箱打开" << endl;
    }
    virtual void turn_off()
    {
        cout << "音箱关闭" << endl;
    }
};

class Gamer
{
public:
    virtual void turn_on()
    {
        cout << "游戏机打开" << endl;
    }
    virtual void turn_off()
    {
        cout << "游戏机关闭" << endl;
    }
};

class Miker
{
public:
    virtual void turn_on()
    {
        cout << "麦克风打开" << endl;
    }
    virtual void turn_off()
    {
        cout << "麦克风关闭" << endl;
    }
};

class DVDPlayer
{
public:
    virtual void turn_on()
    {
        cout << "DVD打开" << endl;
    }
    virtual void turn_off()
    {
        cout << "DVD关闭" << endl;
    }
};

class Client
{
public:
    void KTV()
    {
        cout << "KTV模式" << endl;
        tv.turn_on();
        led.turn_off();
        music_player.turn_on();
        miker.turn_on();
        dvd.turn_on();
    }
    void Game()
    {
        cout << "游戏模式" << endl;
        tv.turn_on();
        music_player.turn_on();
        gamer.turn_on();
    }

private:
    TV tv;
    DVDPlayer dvd;
    Miker miker;
    LED led;
    Gamer gamer;
    MusicPlayer music_player;
};

int main()
{
    Client client;
    client.KTV();
    cout << "------------------------" << endl;
    client.Game();

    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/xiangtingshen/p/10363615.html