/*************************************** **************************************** ***************************/
* Author: Yi Yutian (http://blog.csdn.net/dylgsy ). This article can be ressed casually, but please keep this information
*
* Decorator mode:
* Dynamically add some additional responsibilities to an object. In terms of the added function, the decorator mode is inferior to the subclass generation
* More flexible.
* Because the decorator mode only changes components from the outside, the component does not need to have any knowledge about its decoration. That is to say,
* These decorations are transparent to the component.
/*************************************** **************************************** ***************************/
/*************************************** **************************************** ***************************/
* Instance:
* It is often difficult for children to eat. This requirement may be required before and after meals (difficult to handle ),
* We use the decorator mode to adapt to this special requirement for children to eat.
/*************************************** **************************************** ***************************/
First look at UML:
// Well, let's take a look at the complete sample code:
# Include <iostream>
Using namespace STD;
// Defines the basic interface class and the general method of the Design Mode
Class cchildcomponent
{
Public:
// Children eat
Virtual void eat () = 0;
};
Class cChild: Public cchildcomponent
{
Public:
Virtual void eat ()
{
Cout <"I have eaten. "<Endl;
}
};
// If a child wants to eat an apple before eating, add a modifier class. This class and the Child class are derived from the same parent class.
Class cdecorator: Public cchildcomponent
{
Public:
Cdecorator (cchildcomponent * childcom)
{
_ Child = childcom;
}
Virtual void eat ()
{
}
Protected:
Cchildcomponent * _ child;
};
// Concrete modifier class
Class cchilddecorator: Public cdecorator
{
Public:
Cchilddecorator (cchildcomponent * childcom): cdecorator (childcom)
{
}
Virtual void eat ()
{
Cout <"I want to eat an apple first." <Endl;
_ Child-> eat ();
}
};
// Customer Program
Void main ()
{
// Children eat
CChild child;
Child. Eat ();
// At this time, the child must have a fruit before eating.
// The responsibility of this object is increased.
// The client code is changed:
Cchilddecorator childdec (& Child );
Childdec. Eat ();
// You can see that the above Code seems to have wrapped the child, and it does not know that there is a packaging class to wrap it.
// Meets the OCP principle. In this way, the child will not be afraid of awkwardness.
}