美文网首页
装饰模式

装饰模式

作者: 上海马超23 | 来源:发表于2017-06-24 11:12 被阅读0次
  • 原始组件抽象类Component

    • abstract Operation: 执行原始业务逻辑
  • 原始组件实现类 ConcreteComponent extends Component

    • Operation:实现业务逻辑
  • 抽象装饰类 Decorator extends Component

    • Component属性,通过构造函数传入
    • Operation:也要实现抽象方法,但是一般都交给具体子类去实现装饰的业务逻辑
  • 装饰实现类 ConcreteDecorator extends Decorator

    • 构造函数传入Component被修饰组件
    • Operation:实现装饰逻辑,并调用Component.operation
component = new ConcreteComponent();
component = new ConcreteDecorator1(component);
component = new ConcreteDecorator2(component); // 现在这个原始组件已经被装饰了2次了
component.operator();

总结

优点

  1. Component 和 Decorator 互相不用知道具体的组件,只管调用统一抽象父类的operator方法。
  2. 继承是静态地扩展类的功能,装饰是动态增加;装饰避免了子类的膨胀。
  3. 装饰可以对中间子类做扩展,避免对该子类后续的子孙类改动影响

缺点

避免过多层的装饰,降低系统复杂度

相关文章

网友评论

      本文标题:装饰模式

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