对模块追加功能,比如追加步骤,几行代码,不影响原有功能时使用此模式。
对现有的n个模块追加m种功能,且功能可以按排列组合使用,直接在原有模块上派生会产生很多子类,而且代码重复。
思路:将追加的功能单独抽象成类(装饰器类),并传入原模块指针,这样就能在实现新功能时调用原模块的方法。除此之外,装饰器类还要继承模块类型,继承了之后能够实现追加 功能的复用,原模块的构造器也能用装饰器类初始化;还能重写方法,不用定义新的方法,调用者不用修改代码;声明对象时也能用统一的形式。
下面以扩展component中的foo方法为例。
class component
{
public:
virtual void foo() = 0;
virtual ~component(){}
};
class component_A:public component
{
public:
virtual void foo()
{
cout << "component_A::foo" << endl;
}
};
class component_B :public component
{
public:
virtual void foo()
{
cout << "component_B::foo" << endl;
}
};
class decorate :public component//并不打算使用component,只是为了达到复用功能
{
protected:
component* _component;
public:
decorate(component* component) :_component(component) {}
virtual void foo() = 0;
virtual ~decorate() {}
};
class decorate_A :public decorate
{
public:
decorate_A(component* component):decorate(component){}
virtual void foo()
{
cout << "decorate_A add function" << endl;
decorate::_component->foo();
}
};
class decorate_B :public decorate
{
public:
decorate_B(component* component) :decorate(component) {}
virtual void foo()
{
cout << "decorate_B add function" << endl;
decorate::_component->foo();
}
};
void test03() {
component* a = new component_B;
component* d1 = new decorate_A(a);
component* d2 = new decorate_B(d1);//decorate也能初始化component
d2->foo();//继续调用foo即可
component* a2 = new component_B;
component* d3 = new decorate_B(a2);
component* d4 = new decorate_A(d3);
d4->foo();
delete a;
delete d1;
delete d2;
delete a2;
delete d3;
delete d4;
}