zoukankan      html  css  js  c++  java
  • c++ 装饰模式(decorate)

      装饰模式:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类 更为灵活。有时我们希望给某个对象而不是整个类添加一些功能。比如有一个手机,允许你为手机添加特性,比如增加挂件、屏幕贴膜等。一种灵活的设计方式是, 将手机嵌入到另一对象中,由这个对象完成特性的添加,我们称这个嵌入的对象为装饰。这个装饰与它所装饰的组件接口一致,因此它对使用该组件的客户透明。

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Phone
    {
    public:
        Phone() {}
        virtual ~Phone() {}
        virtual void ShowDecorate() {} 
    };
    
    class iPhone:public Phone
    {
    private:
        string m_name;
    public:
        iPhone(string name):m_name(name){}
        ~iPhone() {}
        void ShowDecorate()
        {
            cout << m_name << "的装饰" <<endl;
        }
    };
    
    class AndroidPhone : public Phone
    {
    private:
        string m_name;
    public:
        AndroidPhone(string name):m_name(name){}
        ~AndroidPhone() {}
        void ShowDecorate()
        {
            cout << m_name << "的装饰" <<endl;
        }
    };
    
    class DecoratorPhone : public Phone
    {
    private:
        Phone *m_phone;
    public:
        DecoratorPhone(Phone *phone):m_phone(phone) {}
        virtual void ShowDecorate()
        {
            m_phone->ShowDecorate();
        }
    };
    
    class DecoratorPhoneA:public DecoratorPhone
    {
    public:
        DecoratorPhoneA(Phone *phone) : DecoratorPhone(phone) {}
        void ShowDecorate() 
        {
            DecoratorPhone::ShowDecorate(); 
            AddDecorate();
        }
    private:
        void AddDecorate()
        {
            cout << "增加挂件" << endl;
        }
    };
    
    int main()
    {
         Phone *dpa = new DecoratorPhoneA(new iPhone("5s"));
         dpa->ShowDecorate();
         delete dpa;
        
         Phone *dpb = new DecoratorPhoneA(new AndroidPhone("Mi2s"));
         dpb->ShowDecorate();
    
         system("pause");
         return 0;
    }

    输出结果:

    5s的装饰
    增加挂件
    Mi2s的装饰
    增加挂件
    请按任意键继续. . .
  • 相关阅读:
    How to change the generated method stub code for C#
    White Paper: Microsoft Data Platform Development
    spring2.5jar包和配置文件总结
    自定义拦截器
    spring+jdbc开发
    Spring Aop支持的两种方式
    C#中Aop编程
    struts2整合spring
    批处理命令总结
    利用datawindow或者datastore的saveas方法导出excell文件,然后修改中文表头
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3480436.html
Copyright © 2011-2022 走看看