装饰器模式

《大话设计模式》

装饰器模式:

为已有功能动态地添加更多功能,当系统需要新功能,向旧的类中添加新功能,装饰了原有类的核心职责和行为,而不改变它们

就像包装袋一样,有新款的包装袋包装之前装好东西的包装袋

//clothes.h
#ifndef _CLOTHES_H_
#define _CLOTHES_H_

#include <string>
using namespace std;

class Person
{
    public:
        Person(char *name):myName(name) {}
        Person() {}
        virtual ~Person() {}
        virtual void Show()
        {
            cout << " 装饰 " << myName << ":\n";
        }
    private:
        string myName;
};

class Finery: public Person
{
    public:
        Finery():m_person(NULL) {}
        virtual ~Finery() {}
        void Decorator(Person *person)
        {
            this->m_person = person;
        }
        void Show()
        {
            m_person->Show();
        }
    private:
        Person *m_person;
};

class TShirts: public Finery
{
    public:
        void Show()
        {
            cout << "大T恤 ";
            Finery::Show();
        }
};

class BigTrouser: public Finery
{
    public:
        void Show()
        {
            cout << "跨裤 ";
            Finery::Show();
        }
};

class Sneakers: public Finery
{
    public:
        void Show()
        {
            cout << "破球鞋 ";
            Finery::Show();
        }
};

class Suit: public Finery
{
    public:
        void Show()
        {
            cout << "西装 ";
            Finery::Show();
        }
};

class Tie: public Finery
{
    public:
        void Show()
        {
            cout << "领带 ";
            Finery::Show();
        }
};

class LeatherShoes: public Finery
{
    public:
        void Show()
        {
            cout << "皮鞋 ";
            Finery::Show();
        }
};


#endif


 

#include <iostream>
#include <cstdio>
#include "clothes.h"

using namespace std;

int main()
{
    
    Person *p = new Person("taotao");
    cout << "装扮: " << endl;
    Sneakers *sneakers = new Sneakers();
    BigTrouser *trouser = new BigTrouser();
    TShirts *tshirts = new TShirts();
    
    sneakers->Decorator(p);
    trouser->Decorator(sneakers);
    tshirts->Decorator(trouser);
    tshirts->Show();
    delete sneakers;
    sneakers = NULL;
    delete trouser;
    trouser = NULL;
    delete tshirts;
    tshirts = NULL;
    delete p;
    p = NULL;
       return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值