.net design patterns - Decorator

Structural Design Patterns: Focus on the relationship between class and class

Decorator: + Inherited manner to extend by a combination of a class, the type of functionality can be added dynamically, even adjustment sequence, without modifying the traffic class;

An abstract class

1   public abstract class AbstractStudent
2     {
3         public int Id { get; set; }
4         public string Name { get; set; }
5 
6         public abstract void Study();
7     }

Inherit the abstract class composition +

 1 public class BaseStudentDecorator : AbstractStudent
 2     {
 3         private AbstractStudent _Student = null;//用了组合加override
 4         public BaseStudentDecorator(AbstractStudent student)
 5         {
 6             this._Student = student;
 7         }
 8 
 9         public override void Study()
10         {
11             this._Student.Study();
12             Console.WriteLine("****************" );
 13              // base class must be empty decorative behavior repeated 
14          }
 15      }

Called Evolution

1  AbstractStudent student = new StudentVip()
2                     {
3                         Id = 1234,
4                         Name = "oldkwok"
5                     };
6                     //BaseStudentDecorator baseStudentDecorator = new BaseStudentDecorator(student);//1 
7                     //AbstractStudent baseStudentDecorator = new BaseStudentDecorator(student);//2
8                     //student = new BaseStudentDecorator(student);//3

Like adapter or a code pattern as would like to extend to a class inheritance and composition it can be divided in two ways

1. Inheritance: Although the time of the call uses only one class, but features a single

2. Combination: Although you can make plenty of expansion (a combination of many types), but call when you need to initialize the proxy class and original class two category

Decorator combines the advantages of both: a call when only the base class to create their implementation, 2 can be made expanded.

 Added functionality can accumulate

. 1 StudentHomeworkDecorator (Student); // . 3 
2                      Student = new new StudentCommentDecorator (Student);
 . 3                      Student = new new StudentHomeworkDecorator (Student); // . 4
 . 4  
. 5                      // Student = new new StudentCommentDecorator (Student);
 . 6                      // not modify the traffic class, free to add functionality decorator
 7                      // can also be adjusted order

The above code is equivalent to adding a decorator to add a function, a pass, a return value is obtained, and the next pass decorator, to give more (more functional) classes, may be understood as a method in the incident added

 

Guess you like

Origin www.cnblogs.com/Spinoza/p/11494954.html