结构型设计模式---装饰者模式(Decorator)

装饰者模式动态地给对象添加新职责,装饰者提供了比继承更有弹性的替代方案

适用场景:
(1)需要扩展一个类的功能,或给一个类增加附加责任。
(2)需要动态地给一个对象增加功能,这些功能可以再动态地撤销。
(3)需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。
优点:
(1)Decorator模式与继承关系的目的都是要扩展对象的功能,但是Decorator可以提供比继承更多的灵活性。
(2)通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。


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

class Phone
{
public:
        virtual ~Phone() { }
        virtual void decoratePhone() = 0;

};

class Iphone : public Phone
{
public:
        Iphone(string name) : m_name(name) {}
        void decoratePhone() { cout << "decorate " << m_name << endl; }

private:
        string m_name;
};

class Mi : public Phone
{
public:
        Mi(string name) : m_name(name) {}
        void decoratePhone() { cout << "decorate " << m_name << endl; }

private:
        string m_name;
};

class DecoratorPhone : public Phone
{
public:
        DecoratorPhone(Phone *phone) : m_phone(phone) {}
        void decoratePhone() { m_phone->decoratePhone(); }

private:
        Phone *m_phone;
};

class DecorateScreen : public DecoratorPhone
{
public:
        DecorateScreen(Phone *phone) : DecoratorPhone(phone) {}
        void decoratePhone()
        {
                DecoratorPhone::decoratePhone();
                enlargeScreen();
        }

private:
        void enlargeScreen() { cout << "enlarge screen" << endl; }
};

class DecorateCraft : public DecoratorPhone
{
public:
        DecorateCraft(Phone *phone) : DecoratorPhone(phone) {}
        void decoratePhone()
        {
                DecoratorPhone::decoratePhone();
                enhanceCraft();
        }

private:
        void enhanceCraft() { cout << "enhance craft" << endl; }
};

int main()
{
        Iphone iphone("Iphone 6");
        Mi mi("MI 3s");

        DecorateScreen ds(&iphone);
        ds.decoratePhone();

        DecorateCraft dc(&mi);
        dc.decoratePhone();

        return 0;
}
                      

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值