Intent:
Dynamically add some additional responsibilities to an object. More flexible than subclass generation
UML structure diagram:
Applicable:
Add roles to a single object dynamically and transparently without affecting other objects
Handle unrecoverable responsibilities
When the subclass generation method cannot be used for expansion, // test. h
/**///////////////////////////////////// //////////////////////////////////////
Class component
{
Public:
Component (){}
Virtual ~ Component (){}
// Pure virtual function
Virtual void operation () = 0;
};
// Abstract the base class to maintain a pointer to the component object
Class decorator: public component
{
Public:
Decorator (component * pcomponent): m_pcomponent (pcomponent ){}
Virtual ~ Decorator ();
Protected:
Component * m_pcomponent;
};
// Derived from component. You need to dynamically add responsibilities to the component.
Class concreatecomponent: public component
{
Public:
Concreatecomponent (){}
Virtual ~ Concreatecomponent (){}
Virtual void operation ();
};
// Derived from decorator, dynamically adding roles for concreatecomponent
Class concreatedecorator: Public decorator
{
Public:
Concreatedecorator (component * pcomponent): decorator (pcomponent ){}
Virtual ~ Concreatedecorator (){}
Virtual void operation ();
PRIVATE:
Void addedbehavior (); // dynamically add responsibilities
};
// Test. cpp: defines the entry point for the console application.
//
# Include "stdafx. H"
# Include <iostream>
# Include "test. H"
//////////////////////////////////////// //////////////////////////////////
Decorator ::~ Decorator ()
{
Delete m_pcomponent;
M_pcomponent = NULL;
}
Void concreatecomponent: Operation ()
{
STD: cout <"Operation of concreatecomponent \ n ";
}
Void concreatedecorator: Operation ()
{
M_pcomponent-> operation ();
Addedbehavior ();
}
Void concreatedecorator: addedbehavior ()
{
STD: cout <"addedbehavior of concreatedecorator \ n ";
}
//////////////////////////////////////// //////////////////////////////////
Int main (INT argc, char * argv [])
{
Component * pcomponent = new concreatecomponent;
// Use this object to initialize a decorator object
// Dynamically add roles through multi-state Invocation
Decorator * pdecorator = new concreatedecorator (pcomponent );
Pdecorator-> operation ();
Delete pdecorator;
System ("pause ");
Return 0;
}