Structure |
|
Intention |
Add some extra responsibilities to an object dynamically. For added functionality, the D e c o r a t o mode is more flexible than generating subclasses. |
Applicability |
- Add responsibilities to a single object in a dynamic, transparent manner without affecting other objects.
- Handle the duties that can be undone.
- When a method of generating subclasses cannot be used for expansion. One scenario is that there may be a large number of independent extensions that will produce a large number of subclasses to support each combination, resulting in an explosive increase in the number of subclasses. Another situation may be because the class definition is hidden, or the class definition cannot be used to generate subclasses.
|
1 usingSystem;2 3 Abstract classComponent4 {5 Public Abstract voidDraw (); 6 }7 8 classconcretecomponent:component9 {Ten Private stringStrName; One PublicConcretecomponent (strings) A { -StrName =s; - } the - Public Override voidDraw () - { -Console.WriteLine ("concretecomponent-{0}", StrName); + } - } + A Abstract classdecorator:component at { - protectedComponent actualcomponent; - - Public voidsetcomponent (Component c) - { -Actualcomponent =C; in } - Public Override voidDraw () to { + if(Actualcomponent! =NULL) - Actualcomponent.draw (); the } * } $ Panax Notoginseng classConcretedecorator:decorator - { the Private stringStrdecoratorname; + PublicConcretedecorator (stringstr) A { the //How decoration occurs was localized inside this decorator + //for this demo, we simply print a decorator name -Strdecoratorname =str; $ } $ Public Override voidDraw () - { - customdecoration (); the Base. Draw (); - }Wuyi voidcustomdecoration () the { -Console.WriteLine ("In concretedecorator:decoration goes here"); WuConsole.WriteLine ("{0}", strdecoratorname); - } About } $ - - /// <summary> - ///Summary description for Client. A /// </summary> + Public classClient the { - Component Setup () $ { theConcretecomponent C =NewConcretecomponent ("This is the real component"); the theConcretedecorator d =NewConcretedecorator ("This was a decorator for the component"); the - d.setcomponent (c); in the returnD; the } About the Public Static intMain (string[] args) the { theClient client =NewClient (); +Component C =client. Setup (); - the //the code below would work equally well with the real component,Bayi //or a decorator for the component the the C.draw (); - - return 0; the } the}
Decoration Mode
Decorative pattern of structural design pattern