<aside> 💡

外观模式(Facade):为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用

</aside>

结构图

image.png

优缺点

优点

缺点

应用场景

题目

https://kamacoder.com/problempage.php?pid=1089

#include <iostream>
#include <string>
using namespace std;

// 子系统类
class AirConditioner{
public:
    void turnOff(){
        cout << "Air Conditioner is turned off." << endl;
    }
};

class DeskLamp{
public:
    void turnOff(){
        cout << "Desk Lamp is turned off." << endl;
    }
};

class Television{
public:
    void turnOff(){
        cout << "Television is turned off." << endl;
    }
};

// 外观类
class DevicesController{
private:
    AirConditioner* airConditioner;
    DeskLamp* deskLamp;
    Television* television;

public:
    DevicesController(){
        airConditioner = new AirConditioner();
        deskLamp = new DeskLamp();
        television = new Television();
    }
    ~DevicesController(){
        delete airConditioner;
        delete deskLamp;
        delete television;
    }

    void turnOffDevice(int action){
        switch(action){
        case 1:
            airConditioner->turnOff();
            break;
        case 2:
            deskLamp->turnOff();
            break;
        case 3:
            television->turnOff();
            break;
        case 4:
            cout << "All devices are off." << endl;
            break;
        default:
            cout << "Invalid device code." << endl;
            break;
        }
    }
};

int main(){
    int n;
    cin >> n;

    DevicesController* devicesController = new DevicesController();
    for(int i = 0; i < n; ++i){
        int action;
        cin >> action;
        devicesController->turnOffDevice(action);
    }
    delete devicesController;

    return 0;
}