美文网首页一步一坑
设计模式- 装饰器模式(Decorator Pattern)

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

作者: 易兒善 | 来源:发表于2019-04-29 11:07 被阅读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();
        }

装饰器模式适用情形:

  • 在不想增加很多子类的情况下扩展一个类的功能
  • 动态增加功能,动态撤销

装饰器模式特点:

  • 可代替继承
  • 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能
  • 多层装饰比较复杂
  • 都必须继承ICommand

其他

源码地址

dotnet-design-patterns

其他设计模式

23种设计模式

相关文章

网友评论

    本文标题:设计模式- 装饰器模式(Decorator Pattern)

    本文链接:https://www.haomeiwen.com/subject/cfaxnqtx.html