现在的位置: 首页 > 综合 > 正文

装饰者模式

2018年04月29日 ⁄ 综合 ⁄ 共 890字 ⁄ 字号 评论关闭
#include <iostream>
using namespace std;

class Person
{
public:
	Person(){}
	Person(const string &n) : name(n) {}

	virtual void show()
	{
		cout <<  name << endl;
	}
private:
	string name;
};

class Finery : public Person
{
public:
	void decorate(Person* comp)
	{
		compenent = comp;
	}
	virtual void show()
	{
		compenent->show();
	}
protected:
	Person* compenent;
};

class Tshirt : public Finery
{
public:
	virtual void show()
	{
		cout << "T-shirt ";
		Finery::show();
	}
};

class Jeans : public Finery
{
public:
	virtual void show()
	{
		cout << "jeans ";
		Finery::show();
		//compenent->show();
	}
};

class suit : public Finery
{
public:
	virtual void show()
	{
		cout << "suit ";
		Finery::show();   //Finery::show()不代表就去调Finery的show,而是调Finery方法的show,即compenent.show() 
		//compenent->show();
	}
};

int main(void)
{
	Person dwc(string("de Tom"));
	Tshirt ts;
	Jeans js;
	suit st;
	ts.decorate(&dwc);  //ts中的 compenont 是dwc 
	js.decorate(&ts);  //js中的 compenont 是ts 
//	js.show();         //js.show() 先show js独有的,即“穿T恤”,然后调 compenont->show(),即ts.show() 
	st.decorate(&js);
	st.show();
	
	return 0;
}

【上篇】
【下篇】

抱歉!评论已关闭.