UML:
Component: defines an object interface that can dynamically add roles to these objects.
Contretecomponent: defines a specific object. You can also add some responsibilities to this object.
Decorator: A decorative abstract class that inherits component and extends the functionality of the component class from external classes. However, for component, you do not need to know the existence of the decrator.
Contretedecoratora and contretedecoratorb are both specific decoration objects. They ride on the function of Adding responsibilities to component.
Sample:
Component. CS
Abstract class component
{
Public abstract void operation ();
}
Concretecomponent. CS
1 Class concretecomponent: Component
2 {
3 Public override void operation ()
4 {
5 Console. writeline ("operations on specific objects ");
6 }
7 }
Decorator. CS
1 Abstract class decorator: Component
2 {
3 Protected component;
4 Public void setcomponent (Component component)
5 {
6 This. Component = component;
7 }
8 Public override void operation ()
9 {
10 If (Component! = NULL)
11 Component. Operation ();
12 }
13 }
Concretedecoratora. CS
1 Class concretedecoratora: decorator
2 {
3 Private string addedstate;
4 Public override void operation ()
5 {
6 Base. Operation ();
7 Addedstate = "new state ";
8 Console. writeline ("actions on decoration object ");
9 }
10 }
Concretedecoratorb. CS
1 Class concretedecoratorb: decorator
2 {
3 Public override void operation ()
4 {
5 Base. Operation ();
6 Addmethod ();
7 Console. writeline ("operations on decoration object B ");
8 }
9 // Used to differentiate method
10 Private void addmethod ()
11 {}
12 }
Program. CS
1 Concretecomponent c = new concretecomponent ();
2 Concretedecoratora d1 = new concretedecoratora ();
3 Concretedecoratorb D2 = new concretedecoratorb ();
4
5 D1.setcomponent (C );
6 D2.setcomponent (D2 );
7 D2.operation ();
The decoration mode uses setcomponent to handle object packaging. in this way, the exclusive implementation of each decoration is separated from how to use this object. Each decoration object only cares about its own functions and does not need to be added to the object chain.