装饰器模式

来源:互联网 发布:淘宝怎么投诉未生产 编辑:程序博客网 时间:2024/06/15 12:33

《大话设计模式》

装饰器模式:

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

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

//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;}