设计模式之装饰模式

装饰模式:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。有时我们希望给某个对象而不是整个类添加一些功能,这样便可以轻而易举的组合出功能各异的对象,而不是从基类到子类专门有一条线来生成这样一个特定功能的对象。

同时可以精简基类的功能,避免在基类中加入更多的只有在特定的情况下才使用到的数据跟方法。

#include "stdafx.h"
#include <memory>
#include <iostream>
#include <string>


class Object
{
private:
	std::string m_strName;
public:
	Object()
	{
	};

	Object(std::string strName)
	{
		m_strName = strName;
	};
	virtual void Show()
	{
		std::cout << m_strName.c_str() << " "<< "dress up" << std::endl;
	}

};

class Person : public Object
{
public:
	Person(std::string strName) : Object(strName)
	{

	};
};

class Finery : public Object
{
protected:
	Object* m_pcomponent;
public:
	void Decorate(Object* pcomponent)
	{
		m_pcomponent = pcomponent;
	}

	virtual void Show()
	{
		if (m_pcomponent != nullptr)
			m_pcomponent->Show();
	}
};

class Tshirts : public Finery
{
public:
	virtual void Show()
	{
		std::cout << "TShirt" << " ";
		Finery::Show();
	}
};

class BigTrousers : public Finery
{
public:
	virtual void Show()
	{
		std::cout << "BigTrouser" << " ";
		Finery::Show();
	}
};

class Shoes : public Finery
{
public:
	virtual void Show()
	{
		std::cout << "Shoe" << " ";
		Finery::Show();
	}
};


int _tmain(int argc, _TCHAR* argv[])
{
	Person p("Jack");
	Tshirts ts;
	ts.Decorate(&p);
	BigTrousers bt;
	bt.Decorate(&ts);
	Shoes sh;
	sh.Decorate(&bt);

	//sh.Show();
	Object* pObj = &sh;
	pObj->Show();
system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值