一步一坑

设计模式- 装饰器模式(Decorator Pattern)

2019-04-29  本文已影响8人  易兒善

定义

装饰器模式(Decorator Pattern):动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活

允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

C#例子

    public interface ICommand
    {
        void Executed();
    }

    public class CreateOrder : ICommand
    {
        public void Executed()
        {
            Console.WriteLine("创建了订单信息!");
        }
    }

    public class WriteLogDecorator : ICommand
    {
        private ICommand _command;
        public WriteLogDecorator(ICommand command) {
            _command = command;
        }
        public void Executed()
        {
            Console.WriteLine("记录了日志!");
            _command.Executed();
        }
    }

    public class PayDecorator : ICommand
    {
        private ICommand _command;
        public PayDecorator(ICommand command)
        {
            _command = command;
        }
        public void Executed()
        {
            _command.Executed();
            Console.WriteLine("支付了完成了!");
        }
    }
    public class StockDecorator : ICommand
    {
        private ICommand _command;
        public StockDecorator(ICommand command)
        {
            _command = command;
        }
        public void Executed()
        {
            _command.Executed();
            Console.WriteLine("扣减了库存!");
        }
    }

        static void Main(string[] args)
        {
            // 记录日志、创建单据
            var cmd1 = new WriteLogDecorator(new CreateOrder());
            cmd1.Executed();
            // 记录日志、创建单据、扣减库存、支付
            var cmd2 = new WriteLogDecorator(new StockDecorator(new PayDecorator(new CreateOrder())));
            cmd2.Executed();
            Console.ReadLine();
        }

装饰器模式适用情形:

装饰器模式特点:

其他

源码地址

dotnet-design-patterns

其他设计模式

23种设计模式

上一篇下一篇

猜你喜欢

热点阅读