装饰模式实现服装搭配

来源:互联网 发布:Json 大括号 编辑:程序博客网 时间:2024/04/27 15:38
#include <iostream>using namespace std;class CPerson{private:string m_sname;public:void SetName(string name){m_sname = name;}~CPerson(){}virtual void ShowAll(){cout << "Person ShowAll" << endl;}};class CDress:public CPerson{protected:CPerson *t_component;public:void Decorate(CPerson *component){t_component = component;cout << "t_component:" << t_component << endl;}void ShowAll(){cout << "t_component:"<<t_component << endl;cout << "Dress ShowAll" << endl;//need to just NULLt_component->ShowAll();}};class CShirts :public CDress{public:void ShowAll(){cout << "CShirts this:" << this << endl;cout << "Shirts!" << endl;CDress::ShowAll();}};class CPants :public CDress{public:void ShowAll(){cout << "this:"<<this << endl;cout << "Pants!" << endl;CDress::ShowAll();}};class CShoes :public CDress{public:void ShowAll(){cout <<"CShoes this:"<< this << endl;cout << "Shoes!" << endl;CDress::ShowAll();}};class CCoats :public CDress{public:void ShowAll(){cout << "CCoats this:" << this << endl;cout << "Coats!" << endl;CDress::ShowAll();}};int main(){CPerson *pMM = new CPerson;pMM->SetName("Han Meimei");CPants *ppant = new CPants;CShoes *pshoes = new CShoes;CShirts *pshirts = new CShirts;ppant->Decorate(pMM);pshoes->Decorate(ppant);pshirts->Decorate(pshoes);pshirts->ShowAll();return 0;}

执行结果:

t_component:011A5598
t_component:011AEF90
t_component:011AF738
CShirts this:011AF698
Shirts!
t_component:011AF738
Dress ShowAll
CShoes this:011AF738
Shoes!
t_component:011AEF90
Dress ShowAll
this:011AEF90
Pants!
t_component:011A5598
Dress ShowAll
Person ShowAll
请按任意键继续. . .


注意Decorate(CPerson *componet)。