C#中增强类功能的几种方式详解

2020-01-05 10:14:17刘景俊
  • 装饰者中对需要增强的方法进行增强,不需要增强的方法调用原来的业务逻辑
    
    namespace Decorator
    {
    
     /// <summary>
     /// Component 抽象者装饰者
     /// </summary>
     public interface IStudent
     {
      void Learn();
     }
    
     /// <summary>
     /// ConcreteComponent 具体被装饰者
     /// </summary>
     public class Student : IStudent
     {
      private string _name;
      public Student(string name)
      {
       this._name = name;
      }
      public void Learn()
      {
       System.Console.WriteLine(this._name + "学习了以上内容");
      }
     }
     /// <summary>
     /// Decorator 装饰者
     /// </summary>
     public abstract class Teacher : IStudent
     {
      private IStudent _student;
      public Teacher(IStudent student)
      {
       this._student = student;
      }
      public virtual void Learn()
      {
       this.Rest();
       this._student.Learn();
      }
    
      public virtual void Rest()
      {
       Console.WriteLine("课间休息");
      }
     }
    
     /// <summary>
     /// ConcreteDecorator 具体装饰者
     /// </summary>
     public class MathTeacher : Teacher
     {
      private String _course;
      public MathTeacher(IStudent student, string course) : base(student)
      {
       this._course = course;
      }
      public override void Learn()
      {
       System.Console.WriteLine("学习新内容:" + this._course);
       base.Learn();
      }
      public override void Rest()
      {
       System.Console.WriteLine("课间不休息,开始考试");
      }
     }
    
     /// <summary>
     /// ConcreteDecorator 具体装饰者
     /// </summary>
     public class EnlishTeacher : Teacher
     {
      private String _course;
      public EnlishTeacher(IStudent student, string course) : base(student)
      {
       this._course = course;
      }
    
      public override void Learn()
      {
       this.Review();
       System.Console.WriteLine("学习新内容:" + this._course);
       base.Learn();
      }
    
      public void Review()
      {
       System.Console.WriteLine("复习英文单词");
      }
     }
    
     public class Program
     {
      static void Main(string[] args)
      {
       IStudent student = new Student("student");
       student = new MathTeacher(student, "高数");
       student = new EnlishTeacher(student, "英语");
       student.Learn();
      }
     }
    }

    装饰者模式优缺点:

    优点:

    • 装饰者与被装饰者可以独立发展,不会互相耦合
    • 可以作为继承关系的替代方案,在运行时动态拓展类的功能