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;
}