设计模式之装饰模式

http://www.jellythink.com/archives/171

装饰模式

题外话:

对一个类a进行功能性增强一般有一下几个方法:

1.直接对类a中代码进行修改;

2.创建一个新类,让它去继承类a;

3.进行内部关联,创建一个新类,让其包含一个a类变量。


特点:

装饰模式动态地给一个对象添加一些额外的功能(它是基于上面第3中形式),就增加功能来说,它比生产子类(继承)更加灵活。

角色:

Component:定义一个对象接口,可以给这些对象动态地添加职责;

ConcreteComponent:定义一个具体的Component,继承自Component,重写了Component类的虚函数;

Decorator:维持一个指向Component对象的指针,该指针指向需要被装饰的对象;并定义一个与Component接口一致的接口;

ConcreteDecorator:向组件添加职责。


class Car{//Component
public:
	virtual void show()=0;
};
class ConcreteCar: public Car{//ConcreteComponent
public:
	void show(){
	cout<<"it can run"<<endl;
	}
};

class Decorator : public Car{//Decorator
public:
	Decorator(Car* c){
		m_car=c;
	}
	virtual void show(){
		if(m_car)
		m_car->show();
	}
private:
 Car* m_car;
};

class SwimCarDecorator:public Decorator{//ConcreteDecorator
public:
	SwimCarDecorator(Car* m):Decorator(m){}
	void show(){
		Decorator::show();
		Swim();
	}
	void Swim(){
		cout<<"it can swim"<<endl;
	}
};
class FlyCarDecorator:public Decorator{//ConcreteDecorator
public:
	FlyCarDecorator(Car* m):Decorator(m){}
	void show(){
		Decorator::show();
		Fly();
	}
	void Fly(){
		cout<<"it can fly"<<endl;
	}
};
int main(){
	Car* car=NULL;
	Decorator* d=NULL;
	car=new ConcreteCar;
	car->show();
	cout<<"----------------------------------"<<endl;
	d=new SwimCarDecorator(car);
	d->show();
	cout<<"----------------------------------"<<endl;
	delete d;
	d=new FlyCarDecorator(car);
	d->show();
	cout<<"----------------------------------"<<endl;
	Decorator* dd=new SwimCarDecorator(d);
	dd->show();
	delete d;
	delete dd;
	delete car;
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值