zoukankan      html  css  js  c++  java
  • 【c++设计模式】外观模式

    结构型模式

    11)外观模式

    本文参考了

    https://www.cnblogs.com/adamjwh/p/9048594.html

    外观模式主要用来为一个复杂的模块或子系统提供一个外界访问的接口。这样使得子系统相对独立,外界对子系统的访问只要黑箱操作即可。
    外观模式一般包含两个角色:
    一个内层系统类,抽象类。
    另一个是外观类,一般不是抽象类。

    比如电脑开机的过程。电脑开机实际上包含了很复杂的过程,包括Cpu,Gpu,内存等设备的开机过程。
    但是作为用户来说,只需要简单得指示电脑开机就可以了,不需要知道具体的细节。

    //内存系统类
    class Device{
    public:
        virtual void startUp() = 0;
        virtual void shutDown() = 0;
    };
    
    class Cpu:public Device{
    public:
        void startUp(){
            cout<<"Cpu is starting up..."<<endl;
        }
        void shutDown(){
            cout<<"Cpu is shutting down..."<<endl;
        }
    };
    
    class Gpu:public Device{
    public:
        void startUp(){
            cout<<"Gpu is starting up..."<<endl;
        }
        void shutDown(){
            cout<<"Gpu is shutting down..."<<endl;
        }
    };
    
    class Memory : public Device{
    public:
        void startUp(){
            cout<<"Memory is starting up..."<<endl;
        }
        void shutDown(){
            cout<<"Memory is shutting down..."<<endl;
        }
    };
    
    //外观类
    class Computer{
    public:
        Computer(){
            m_cpu = new Cpu();
            m_gpu = new Gpu();
            m_memory = new Memory();
        }
        void startUp(){
            m_cpu->startUp();
            m_gpu->startUp();
            m_memory->startUp();
        }
        
        void shutDown(){
            m_cpu->shutDown();
            m_gpu->shutDown();
            m_memory->shutDown();
        }
    private:
        Cpu* m_cpu;
        Gpu* m_gpu;
        Memory* m_memory;
    };
    
    int main(){
        Computer* c = new Computer();
        c->startUp();
        cout<<"===="<<endl;
        c->shutDown();
    }
    
    
    

    运行结果为:

  • 相关阅读:
    CTSC2018滚粗记
    HNOI2018游记
    NOIWC 2018游记
    PKUWC2018滚粗记
    HNOI2017 游记
    NOIP2017题解
    [HNOI2017]抛硬币
    [HNOI2017]大佬
    NOIP难题汇总
    [NOI2013]树的计数
  • 原文地址:https://www.cnblogs.com/corineru/p/12019928.html
Copyright © 2011-2022 走看看