Decoration Mode
A. Definition:
Dynamically add some responsibilities to an object. The modifier mode is more flexible than the subclass generation function.
B. Definition Analysis:
"DynamicallyAdd some responsibilities to an object. The modifier mode is more flexible than the subclass generation function. "We know that the responsibility of an object is defined in the class, and the class method determines the responsibility of the object.
"Dynamically add some responsibilities to an object. The modifier mode is more flexible than the subclass generation function. "The decorator mode aims to dynamically add roles to objects without modifying classes.
"Dynamically add some responsibilities to an object.The modifier mode is more flexible than the subclass generation function."The modifier does not modify the class, But dynamically adds the object, of course, flexible.
C. Question:
(1) how to implement it?
Suppose there are classes A and Suba, and Suba inherits from a.a. There is an interface dress that indicates wearing clothes.
1 Class A
2 {
3 Virtual Void Dress ( Void ) = 0 ;
4 };
5 Class Suba: Public A
6 {
7 Void Dress ( Void )
8 {
9 // Wear a T-shirt.
10 }
11 };
However, we suddenly want to extend the dress interface, but do not want to change a and Suba. At this time, we use the decoration mode:
ClassDecoratorhat:PublicA
{
A * m_p;
Decoratorhat (A * P)
: ()
{
M_p = P;
}
VoidDress (Void)
{
//Hats
M_p-> dress ();
}
};
ClassDecoratorglass:PublicA
{
A * m_p;
Decoratorglass (A * P)
: ()
{
M_p = P;
}
VoidDress (Void)
{
//Wear glasses
M_p-> dress ();
}
};
Decoratorhat and decoratorglass are the decorators. They can be used as follows:
A * P = NULL;
P =NewDecoratorhat (NewDecoratorglass (NewSuba ));
P-> dress ();
At this time, Suba will be decorated.