C# 中的装饰器模式示例

装饰器模式属于结构型模式,它是作为现有的类的一个包装。
允许向一个现有的对象添加新的功能,同时又不改变其结构。

这种模式创建了一个装饰类,用来包装原有的类,
并在保持类方法签名完整性的前提下,提供了额外的功能。

    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 的管道很相似。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值