Decoration Mode
Definition:
Dynamically add some additional responsibilities to an object. As for the added function, the decoration mode is more flexible than the subclass generation.
Applicability:
1. Add roles to a single object dynamically and transparently without affecting other objects.
2. Handle revoking duties
3. When the subclass generation method cannot be used, the extension is.
Advantages:
1. more flexible than static inheritance
2. avoid having too many features in the class at the upper level of the hierarchy.
Structure:
Implementation:
Class Component
{
Public:
Component (){};
Virtual ~ Component (){};
Virtual void doSomething () = 0;
};
Class A: public Component
{
Public:
VoiddoSomething (){}
Protected:
Private:
};
Class ConcreteComponent: public Component
{
Public:
ConcreteComponent (){}
~ ConcreteComponent (){}
VoiddoSomething ()
{
Cout <"ConcreteComponent doSomething" <
}
};
Class Decorator: public Component
{
Public:
Decorator (Component * pcomponent): m_pComponent (pcomponent)
{}
~ Decorator (){}
// Directly call the decorated component
VoiddoSomething ()
{
M_pComponent-> doSomething ();
}
Private:
Component * m_pComponent;
};
// Adds an additional State to ConcreteComponent
Class ConcreteDecoratorA: public Decorator
{
Public:
ConcreteDecoratorA (Component * pcomponent, string name): Decorator (pcomponent), m_name (name)
{}
~ ConcreteDecoratorA (){}
VoiddoSomething ()
{
Cout <"ConcreteComponent name:" <
Decorator: doSomething ();
}
Private:
// Additional status
String m_name;
};
// Added additional operations to ConcreteComponent
Class ConcreteDecoratorB: public Decorator
{
Public:
ConcreteDecoratorB (Component * pcomponent): Decorator (pcomponent)
{}
~ ConcreteDecoratorB (){}
VoiddoSomething ()
{
DoAdditionalThing ();
Decorator: doSomething ();
}
Private:
// Additional responsibilities
VoiddoAdditionalThing ()
{
Cout <"ConcreteDecoratorB doAdditionalThing" <
}
};
Component * pcom = new ConcreteComponent;
Decorator * pa = newConcreteDecoratorA (pcom, "componentA ");
Decorator * pb = newConcreteDecoratorB (pcom );
Pa-> doSomething ();
Pb-> doSomething ();
The most important thing in implementation is that the interface between the decoration object and the decorated component is consistent. If there are multiple decoration classes, all the decoration classes must have a common parent class.