// 装饰模式:动态的给一个对象添加一些额外的职责,对于增加功能来说,装饰模式比生产子类更灵活;
// 人 class Person { public: Person(void); ~Person(void); Person(std::string name) { m_name = name; } virtual void Show() { cout<<"装扮的"<<m_name<<endl; } private: string m_name; };
// 装饰类; class Finery : public Person { public: Finery(void); virtual~Finery(void); void Decorate(Person *pPerson) { m_pPerson = pPerson; } void Show() { if (m_pPerson) { m_pPerson->Show(); } } private: Person *m_pPerson; }; class BigTrouser : public Finery { public: BigTrouser(void); ~BigTrouser(void); void Show() { cout<<"垮裤"<<endl; Finery::Show(); } };
class Sneakers : public Finery { public: Sneakers(void); ~Sneakers(void); void Show() { cout<<"破球鞋"<<endl; Finery::Show(); } };
class TShirts : public Finery { public: TShirts(void); ~TShirts(void); void Show() { cout<<"大T衣"<<endl; Finery::Show(); } };
#include "Sneakers.h" #include "BigTrouser.h" #include "TShirts.h" // 装饰模式:动态的给一个对象添加一些额外的职责,对于增加功能来说,装饰模式比生产子类更灵活; int _tmain(int argc, _TCHAR* argv[]) { Person *pPerson = new Person("小菜"); Sneakers* pSneakers = new Sneakers; BigTrouser* pBigTrouser = new BigTrouser; TShirts* pTShirts = new TShirts; pSneakers->Decorate(pPerson); pBigTrouser->Decorate(pSneakers); pTShirts->Decorate(pBigTrouser); pTShirts->Show(); if (pPerson) { delete pPerson; pPerson = NULL; } if (pSneakers) { delete pSneakers; pSneakers = NULL; } if (pBigTrouser) { delete pBigTrouser; pBigTrouser = NULL; } if (pTShirts) { delete pTShirts; pTShirts = NULL; } return 0; }