1.为什么要使用装饰者模式
首先实现一个学生学习的功能,实例化一个学生对象,然后调用学生的学习方法,
现在有新的需求,学生学习前需要预习课程,学习后需要复习课程,老师答疑。
要求:在不改动原有封装的前提下实现以上功能。
在这种情况下,就得使用AOP(面向切面编程)编程思想,
我们就用 继承+组合 装饰者模式来实现AOP
2.装饰者模式的实现
实现要素:
- 抽象装饰对象
- 具体装饰对象
- 抽象装饰器
- 具体装饰器
代码实现
/// <summary>
/// 抽象学生
/// </summary>
public abstract class AbstractStudent
{
public string Name { get; set; }
public abstract void Study();
}
/// <summary>
/// 具体学生
/// </summary>
public class Student : AbstractStudent
{
public override void Study()
{
Console.WriteLine($"{base.Name} 开始学习!");
}
}
/// <summary>
/// 抽象装饰者 继承+组合
/// </summary>
public abstract class AbstractStudentDecorator : AbstractStudent
{
private AbstractStudent _AbstractStudent = null;
public AbstractStudentDecorator(AbstractStudent abstractStudent)
{
this._AbstractStudent = abstractStudent;
}
public override void Study()
{
_AbstractStudent.Study();
}
}
/// <summary>
/// 答疑装饰器
/// </summary>
public class StudentDecoratorAnswer : AbstractStudentDecorator
{
public StudentDecoratorAnswer(AbstractStudent abstractStudent)
:base(abstractStudent)
{
}
public override void Study()
{
base.Study();
Console.WriteLine("老师答疑");
}
}
/// <summary>
/// 预习装饰器
/// </summary>
public class StudentDecoratorPreview : AbstractStudentDecorator
{
public StudentDecoratorPreview(AbstractStudent abstractStudent)
:base(abstractStudent)
{
}
public override void Study()
{
Console.WriteLine("在上课前预习一下");
base.Study();
}
}
/// <summary>
/// 复习装饰器
/// </summary>
public class StudentDecoratorReview : AbstractStudentDecorator
{
public StudentDecoratorReview(AbstractStudent abstractStudent)
:base(abstractStudent)
{
}
public override void Study()
{
base.Study();
Console.WriteLine("在课后复习一下");
}
}
前台调用:
static void Main(string[] args)
{
{
AbstractStudent student = new Student()
{
Name = "张三"
};
student = new StudentDecoratorPreview(student);
student = new StudentDecoratorAnswer(student);
student = new StudentDecoratorReview(student);
student.Study();
}
Console.ReadKey();
}
以上便实现了装饰者模式。
3.总结一下
装饰器模式适用于在不破坏原有封装的前提下,实现功能的扩展,使得程序扩展方便。