十分钟学会一个设计模式---结构模式---外观模式(门面模式)

104 阅读1分钟
  1. 为一个或多个子系统复杂逻辑提供一个简单接口,降低访问复杂系统的内部子系统时的复杂度
  2. 管理子系统对象的生命周期
// 子系统1
class System1 {
public:
    string Operation1() const {
        return "system1 operation1; ";
    }

    string Operation2() const {
        return "system1 operation2; ";
    }
};
// 子系统2
class System2 {
public:
    string Operation1() const {
        return "system2 operation1; ";
    }

    string Operation2() const {
        return "system2 operation2; ";
    }
};
// 门面,内部有多个子系统,封装一个方法对外使用
class Facade {
private:
    System1 *system1;
    System2 *system2;
public:
    Facade(System1 *system11 = nullptr, System2 *system21 = nullptr) {
        this->system1 = system11 ?: new System1;
        this->system2 = system21 ?: new System2;
    }

    ~Facade() {
        delete system1;
        delete system2;
    }

    string Operation() {
        string result = "Operation1 ";
        result += this->system1->Operation1();
        result += this->system2->Operation1();
        result += "Operation2 ";
        result += this->system1->Operation2();
        result += this->system2->Operation2();
        return result;
    }
};

int main() {
    System1 *system1 = new System1;
    System2 *system2 = new System2;
    Facade *facade = new Facade(system1, system2);
    cout << facade->Operation();
    delete facade;
}