美文网首页
装饰者模式

装饰者模式

作者: StevenHD | 来源:发表于2021-01-10 12:30 被阅读0次

    一、装饰者模式

    图解

    如何不依赖于Nokia类,直接用耳机类本身来返回实例。

    二、示例代码

    #include <iostream>
    
    using namespace std;
    
    class Phone
    {
    public:
        virtual int cost() = 0;
    };
    
    class Nokia : public Phone
    {
    public:
        virtual int cost()
        {
            return 5000;
        }
    };
    
    class DecoratePhone : public Phone
    {
    public:
        DecoratePhone(Phone* ph) : _phone(ph) {}
    
    protected:
        Phone * _phone;
    };
    
    class ScreenProtecterPhone : public DecoratePhone
    {
    public:
        ScreenProtecterPhone(Phone *ph) : DecoratePhone(ph) {}
    
        virtual int cost()
        {
            return 100 + _phone->cost();
        }
    };
    
    class HeadSetPhone : public DecoratePhone
    {
    public:
        HeadSetPhone(Phone *ph) : DecoratePhone(ph) {}
    
        virtual int cost()
        {
            return 200 + _phone->cost();
        }
    };
    
    int main()
    {
        Nokia nk;
        cout << nk.cost() << endl;
    
        ScreenProtecterPhone sp(&nk);
        cout << sp.cost() << endl;
        
    
    //    ScreenProtecterPhone sp2(&sp);
    //    cout << sp2.cost() << endl;
    
        HeadSetPhone hp(&sp);
        cout << hp.cost() << endl;
    
        Phone *p = new HeadSetPhone(new ScreenProtecterPhone(new HeadSetPhone(new ScreenProtecterPhone(new Nokia))));
        cout << p->cost() << endl;
    
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:装饰者模式

          本文链接:https://www.haomeiwen.com/subject/zfpwiktx.html