装饰模式

针对的问题

1)需要扩展一个类的功能,或给一个类增加附加责任。

2)需要动态的给一个对象增加功能,这些功能可以再动态地撤销。

UML

在这里插入图片描述

代码

#include<iostream>
using namespace std;
class person
{
public:
	void show()
	{
		cout<<"出门穿衣服"<<endl;
	}
};
class decorate:public person
{
public:
	virtual void set(person *p)=0;
private:
	person *p;
};
class ClothesRed:public decorate
{
public:
	void set(person *p)
	{
		this->CRed = p;
		CRed->show();
		cout<<"红衣服"<<endl;
	}
private:
	person *CRed;
};
class ClothesBlue:public decorate
{
public:
	void set(person *p)
	{
		this->CBlue = p;
		CBlue->show();
		cout<<"蓝衣服"<<endl;
	}
private:
	person *CBlue;
};
class PantRed:public decorate
{
public:
	void set(person *p)
	{
		this->PRed = p;
		PRed->show();
		cout<<"红裤子"<<endl;
	}
private:
	person *PRed;
};
class PantBlue:public decorate
{
public:
	void set(person *p)
	{
		this->PBlue = p;
		PBlue->show();
		cout<<"蓝裤子"<<endl;
	}
private:
	person *PBlue;
};
int main()
{
	person *p = new person;
	decorate *cred = new ClothesRed;
	decorate *cblue = new ClothesBlue;
	decorate *pred = new PantRed;
	decorate *pblue = new PantBlue;
	cred->set(p);
	pblue->set(p);
	system("pause");
	return 0;
}

总结

装饰模式有效地把类的核心职责和装饰功能区分开,可以去除相关类中的重复装饰逻辑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值