c++外观模式

2021-02-14  本文已影响0人  一路向后

1.外观模式简介

   外观(Facade)模式又叫作门面模式,是一种通过为多个复杂的子系统提供一个一致的接口,而使这些子系统更加容易被访问的模式。该模式对外有一个统一接口,外部应用程序不用关心内部子系统的具体细节,这样会大大降低应用程序的复杂度,提高了程序的可维护性。

2.源码实现

#include <iostream>
#include <string>

using namespace std;

//子工作1
class SubWork1
{
public:
    void Working()
    {
        cout << "Doing Sub-Work1..." << endl;
    }
};

//子工作2
class SubWork2
{
public:
    void Working()
    {
        cout << "Doing Sub-Work2..." << endl;
    }
};

//子工作3
class SubWork3
{
public:
    void Working()
    {
        cout << "Doing Sub-Work3..." << endl;
    }
};

//子工作4
class SubWork4
{
public:
    void Working()
    {
        cout << "Doing Sub-Work4..." << endl;
    }
};

class Work
{
private:
    SubWork1 w1;
    SubWork2 w2;
    SubWork3 w3;
    SubWork4 w4;

public:
    void Work1()
    {
        w1.Working();
        w3.Working();
    }

    void Work2()
    {
        w2.Working();
        w3.Working();
        w4.Working();
    }
};

int main(int argc, char **argv)
{
    Work w;

    cout << "开始调用总工作1" << endl;

    w.Work1();

    cout << "开始调用总工作2" << endl;

    w.Work2();

    return 0;
}

3.编译源码

$ g++ -o example example.cpp

4.运行及其结果

$ ./example
开始调用总工作1
Doing Sub-Work1...
Doing Sub-Work3...
开始调用总工作2
Doing Sub-Work2...
Doing Sub-Work3...
Doing Sub-Work4...
上一篇下一篇

猜你喜欢

热点阅读