#include <iostream>
using namespace std;
//Person作为父类,定义一个对象接口,也定义一个具体对象,也可以给这些对象动态地添加职责。。
class Person
{
private:
string name;
public:
Person()
{
}
Person(string n)
{
this->name = n;
}
virtual void Show()
{
cout<<"装扮的"<<this->name<<endl;
}
};
//Finery继承Person,作为装饰抽象类,从Finery的派生类来拓展Person类的功能
class Finery : public Person
{
protected:
Person* component;
public:
void Decorate (Person *p)
{
this->component = p;
}
virtual void Show()
{
if(component != NULL)
{
component->Show();
}
}
};
//TShirts继承Finery,具体的装饰对象,起到给Person添加职责装饰的功能
class TShirts:public Finery
{
public:
virtual void Show()
{
cout<<"大T恤"<<endl;
Finery::Show();
}
};
//BigTrouser继承Finery,具体的装饰对象,起到给Person添加职责装饰的功能
class BigTrouser:public Finery
{
public:
virtual void Show()
{
cout<<"垮裤"<<endl;
Finery::Show();
}
};
//SportShoes继承Finery,具体的装饰对象,起到给Person添加职责装饰的功能
class SportShoes:public Finery
{
public:
virtual void Show()
{
cout<<"运动鞋"<<endl;
Finery::Show();
}
};
//LeatherShoes继承Finery,具体的装饰对象,起到给Person添加职责装饰的功能
class LeatherShoes:public Finery
{
public:
virtual void Show()
{
cout<<"皮鞋"<<endl;
Finery::Show();
}
};
//Suit继承Finery,具体的装饰对象,起到给Person添加职责装饰的功能
class Suit:public Finery
{
public:
virtual void Show()
{
cout<<"西装"<<endl;
Finery::Show();
}
};
//Tie继承Finery,具体的装饰对象,起到给Person添加职责装饰的功能
class Tie:public Finery
{
public:
virtual void Show()
{
cout<<"领带"<<endl;
Finery::Show();
}
};
/*
装饰的方法是:先用Person实例化对象xc,然后用SportShoes实例化对象ss来装饰包装xc,
再用BigTrouser实例化对象bt来装饰包装ss,
再用TShirts实例化对象bt来装饰包装bt,
最终执行ts的Show()。(一层一层包装)
*/
int main()
{
Person *xc = new Person("小菜");
cout<<"第一种打扮"<<endl;
SportShoes *ss = new SportShoes();
BigTrouser *bt = new BigTrouser();
TShirts *ts = new TShirts();
ss->Decorate(xc);
bt->Decorate(ss);
ts->Decorate(bt);
ts->Show();
system("pause");
return 0;
}
设计模式——装饰者模式(C++)——小菜扮靓
最新推荐文章于 2023-08-01 22:13:10 发布