The decorative pattern that arises from the problems encountered
In the OO design and development process, you may often experience the following situations: We need to add new responsibilities (operations) to a defined class, and usually we will inherit a custom class from the definition of a new class, which will create a problem (to be given in the discussion of this pattern). Resolving such situations through inheritance also brings complexity to the system, as the depth of inheritance becomes deep.
Decoration provides a way to add responsibilities to a class, not through inheritance, but by combining.
These elements are further elaborated in the discussion.
mode selection
The typical structure of the decoration pattern is:
In a structure diagram, concretecomponent and decorations need to have the same interface, so concretecomponent and decoration have a common parent class. Some people will ask, let the decoration directly maintain a point to concretecomponent reference (pointer) can not achieve the same effect, the answer is yes and is negative. It is certain that you can do it in this way, and that you do not do it this way, because in this way you can only provide cosmetic operations for this particular concretecomponent, and when you have a new concretecomponent you have to create another one. Is. But with a common base class in the concretecomponent and ornamentation of the chart, you can use the idea of OO polymorphism to implement a class that can provide cosmetic operations for objects of Component type, in which case you create a new 100 Component Type other class Concretecomponent, also can be decorated by a class. This is also the key and power of the decorative model.
Of course, if you only add a modification to the Component type class, it is not necessary to decorate the base class.
Instance
#include <iostream>
using namespace std;
Class Testa
{public
:
void Display_a ()
{
cout<< "display a ..." <<endl;
}
};
Class Testb
{public
:
void Display_b ()
{
cout<< "Display b ..." <<endl;
}
};
class Façade
{
testa *testa;
Testb *testb;
Public:
façade ()
{
testa = new Testa ();
TESTB = new Testb ();
}
~facade ()
{
delete testa;
Delete testb;
}
void MethodA ()
{
testa->display_a ();
Testb->display_b ();
}
;
int main ()
{
façade *facade = new façade ();
Facade->methoda ();
System ("pause");
return 0;
}