C#装饰器模式解析

装饰器模式优缺点及使用场景
优点:灵活,扩展性好,能够在不影响业务类的前提下,动态的为其添加本身不存在的功能
缺点:增加了程序的复杂程度
使用场景:为具体的业务对象附加功能职责,例如上述的游戏装备,以及培训班的各层vip,商场的多重优惠等等
/// <summary>
/// 实体类
/// </summary>
public class Student : AbstractStudent
{
    public override void Study()
    {
        Console.WriteLine("白天学习!!!");
    }
}
/// <summary>
/// 抽象类
/// </summary>
public abstract class AbstractStudent
{
    public int id;
    public string Name;
    public abstract void Study();
}
/// <summary>
/// 装饰器基类
/// </summary>
public class DecoratorBase : AbstractStudent
{
    private AbstractStudent _student;
    public DecoratorBase(AbstractStudent student)
    {
        this._student = student;
    }
    public override void Study()
    {
        _student.Study();
    }
}
 /// <summary>
 /// 装饰器
 /// </summary>
 public class DecoratorStudentAnser : DecoratorBase
 {
     public DecoratorStudentAnser(AbstractStudent student) : base(student)
     {
     }
     public override void Study()
     {
         base.Study();
         Console.WriteLine("作业巩答疑");
     }
 }
/// <summary>
/// 装饰器
/// </summary>
public class DecoratorStudentHomeworke : DecoratorBase
{
    public DecoratorStudentHomeworke(AbstractStudent student) : base(student)
    {
    }
    public override void Study()
    {
        base.Study();
        Console.WriteLine("作业巩固练习");
    }
}
/// <summary>
/// 装饰器
/// </summary>
public class DecoratorStudentPreview : DecoratorBase
{
    public DecoratorStudentPreview(AbstractStudent student) : base(student)
    {
    }
    public override void Study()
    {
        Console.WriteLine("课前预习");
        base.Study();
    }
}
/// <summary>
/// 装饰器
/// </summary>
public class DecoratorStudentVideo : DecoratorBase
{
    public DecoratorStudentVideo(AbstractStudent student) : base(student)
    {
    }
    public override void Study()
    {
        base.Study();
        Console.WriteLine("课后获取回看视频");
    }
}

以下是调用
static void Main(string[] args)
{
    AbstractStudent student = new Student();
    student.id = 888;
    student.Name = "罗分明";
    //DecoratorStudentVideo studentVideo = new DecoratorStudentVideo(student);//1、组合实例化
    //DecoratorBase studentVideo=new DecoratorStudentVideo(student);//2、左边换成父类
    //AbstractStudent studentVideo = new DecoratorStudentVideo(student);//3、左边换成父类

    student = new DecoratorStudentVideo(student);//4、把新变量引用指向改变,合并变量
    student = new DecoratorStudentHomeworke(student);
    student = new DecoratorStudentAnser(student);

    student = new DecoratorStudentPreview(student);
    student.Study();
    //转载请保留http://www.luofenming.com/show.aspx?id=ART2019052600001
}

以下是运行结果

评论