装饰器模式属于结构型模式,它是作为现有的类的一个包装。
允许向一个现有的对象添加新的功能,同时又不改变其结构。
这种模式创建了一个装饰类,用来包装原有的类,
并在保持类方法签名完整性的前提下,提供了额外的功能。
public abstract class AbstractMotion
{
public abstract void Start();
}
public class BaseMotion : AbstractMotion
{
private readonly AbstractMotion _motion;
public BaseMotion(AbstractMotion motion) { _motion = motion; }
public override void Start()
{
Console.WriteLine("base start.");
_motion.Start();
Console.WriteLine("base end.");
}
}
public class WarmUp : AbstractMotion
{
public override void Start()
{
Console.WriteLine("热身.");
}
}
public class Jump : BaseMotion
{
public Jump(AbstractMotion motion) : base(motion) { }
public override void Start()
{
Console.WriteLine("跳跃 start.");
base.Start();
Console.WriteLine("跳跃 end.");
}
}
public class Run : BaseMotion
{
public Run(AbstractMotion motion) : base(motion) { }
public override void Start()
{
Console.WriteLine("跑步 start.");
base.Start();
Console.WriteLine("跑步 end.");
}
}
public class Walk : BaseMotion
{
public Walk(AbstractMotion motion):base(motion) { }
public override void Start()
{
Console.WriteLine("步行 start.");
base.Start();
Console.WriteLine("步行 end.");
}
}
调用
static void Main(string[] args)
{
AbstractMotion motion = new WarmUp();
motion = new Walk(motion);
motion = new Run(motion);
motion = new Jump(motion);
motion.Start();
}
得到的控制台为:
跳跃 start.
base start.
跑步 start.
base start.
步行 start.
base start.
热身.
base end.
步行 end.
base end.
跑步 end.
base end.
跳跃 end.
装饰器模式 和 ASP.NET Core 的管道很相似。