//decorator.h #ifndef AFX_CLASS_CONCRETECOMPONENT #define AFX_CLASS_CONCRETECOMPONENT class Person { public: Person() { } Person( string name ) { this->name = name; } virtual void Show() { cout<< "装扮的" << name << endl; } private: string name; }; #endif #ifndef AFX_CLASS_DECORATOR #define AFX_CLASS_DECORATOR class Finery:public Person { public: void Decorate( Person *component ) { this->component = component; } virtual void Show( ) { if( component != NULL ) { component->Show(); } } protected: Person *component; }; #endif #ifndef AFX_CLASS_CONCRETEDECORATOR #define AFX_CLASS_CONCRETEDECORATOR class TShirts:public Finery { public: virtual void Show( ) { cout<< "大T桖" << endl; Finery::Show(); } }; class BigTrouser:public Finery { public: virtual void Show( ) { cout<< "跨裤" << endl; Finery::Show(); } }; class Sneakers:public Finery { public: virtual void Show( ) { cout<< "破球鞋" << endl; Finery::Show(); } }; class Suit:public Finery { public: virtual void Show( ) { cout<< "西装" << endl; Finery::Show(); } }; class Tie:public Finery { public: virtual void Show( ) { cout<< "领带" << endl; Finery::Show(); } }; class LeatherShoes:public Finery { public: virtual void Show( ) { cout<< "皮靴" << endl; Finery::Show(); } }; #endif #include <iostream> #include <string> #include <conio.h> using namespace std; #include "decorator.h" int main( int argc , char *argv[] ) { Person *xc = new Person( "小菜" ); cout<< "第一种装扮" <<endl; Sneakers *pqx = new Sneakers(); BigTrouser *kk = new BigTrouser(); TShirts *dtx = new TShirts(); pqx->Decorate( xc ); kk->Decorate( pqx ); dtx->Decorate( kk ); dtx->Show(); cout<< "第二种装扮" <<endl; LeatherShoes *px = new LeatherShoes(); Tie *ld = new Tie(); Suit *xz = new Suit(); px->Decorate(xc); ld->Decorate(px); xz->Decorate(ld); xz->Show(); getch(); return 1; }