设计模式 之 装饰模式

装饰模式(Decorator):动态地给对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。装饰模式结构图如下:
在这里插入图片描述
装饰模式代码模型

//Component类
class Component
{
public:
	void Operation();
};
//ConcreteComponent类
class ConcreteComponent : public Component
{
public:
	Operation()
	{
		cout<<"具体对操作"}
};
//Decorator类
class Decorator:public  Component
{
protected:
	Component component;
public:
//设置Component 
	void setComponent(Component component)
	{
		this.Component = component;
	}
	//重写Operation()实际执行的是Component 的Operation()
	void Operation()
	{
		component.Operation();
	}
};
class ConcreteDecoratorA:Decorator
{
	private:
	//本类独有功能,以区别ConcreteDecoratorB
	string addState;
	public:
	void Operation()
	{
	//首先运行原Component的Operation。再执行本类的功能,如addState ,相当于对原Component进行了修饰
		Component::Operation();
		addState = "New State";
		cout<<"具体装饰对象A的操作";
	}
};
class ConcreteDecoratorB:Decorator
{
	void Operation()
	{
	//首先运行原Component的Operation。再执行本类的功能,如AddBehavior(),相当于对原Component进行了修饰
		Component::Operation();
		AddBehavior();
		cout<<"具体装饰对象B的操作";
	}
	private:
	//本类独有的方法,以区别与ConcreteDecoratorA
	void AddBehavior()
	{
	}
};

void main()
{
	ConcreteDecorator *c = new ConcreteDecorator ();
	ConcreteDecoratorA *d1 = new ConcreteDecoratorA ();
	ConcreteDecoratorB *d2 = new ConcreteDecoratorB;
	//装饰的方法是:首先用ConcreteDecorator 实例化对象c,然后用ConcreteDecoratorA 的实例化对象d1来包装c,再用ConcreteDecoratorB的实例化对象d2包装d1,最后执行d2的Operation
	d1->setComponent(c);
	d2->setComponent(d1);
	d2->Operation();
}

装饰模式利用setComponent来对对象进行包装,每个装饰对象的实现就和如何使用这个对象分离开,每个装饰对象只关心自己的功能,不需要关心如何让被添加到对象链当中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值