装饰者模式——探索之旅

装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

#pragma once

#include <iostream>
using namespace std;

struct IComponent
{
	virtual void operation() = 0;
};

class ConcreteComponent :public IComponent
{
public:
	void operation()
	{
		cout << "call ConcreteComponent operation" << endl;
	}
};

class Decorator :public IComponent
{
public:
	Decorator()
		:_comp(nullptr)
	{}
	virtual ~Decorator()
	{
		delete _comp;
		_comp = nullptr;
	}
	virtual void operation()
	{
		_comp->operation();
		cout << "call Decorator operation" << endl;
	}
	virtual	void setComponent(IComponent* comp)
	{
		_comp = comp;
	}
protected:
	IComponent* _comp;
};

class ConcreteDecoratorA :public Decorator
{
public:
	virtual void operation()
	{
		_comp->operation();
		addedState();
		cout << "call ConcreteDecoratorA operation" << endl;
	}
	virtual void addedState()
	{
		cout << "call ConcreteDecoratorA addedState" << endl;
	}
};

class ConcreteDecoratorB :public Decorator
{
public:
	virtual void operation()
	{
		_comp->operation();
		addedBehavior();
		cout << "call ConcreteDecoratorB operation" << endl;
	}
	virtual void addedBehavior()
	{
		cout << "call ConcreteDecoratorB addedBehavior" << endl;
	}
};

void decoratorTest()
{
	IComponent *concreteComp = new ConcreteComponent;
	Decorator *concreteDectA = new ConcreteDecoratorA;
	concreteDectA->setComponent(concreteComp);
	concreteDectA->operation();
	Decorator *concreteDectB = new ConcreteDecoratorB;
	concreteDectB->setComponent(concreteDectA);
	concreteDectB->operation();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值