美文网首页
设计模式-装饰模式

设计模式-装饰模式

作者: ZjyMac | 来源:发表于2018-05-07 13:57 被阅读0次

一,装饰模式详解

  • 概念
    装饰模式:动态的给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活,装饰模式是一种对象结构型模式
  • 使用场景
    (1)在不影响其他对象的情况下,以动态,透明的方式给单个对象添加职责
    (2)当不能采用继承的方式对系统进行扩展或者采用继承不利于系统的扩展和维护可以使用装饰模式
  • UML
    image.png
  • 代码示例
public interface Component {
   void operation();
}
public class ConcreteComponent implements Component{
    @Override
    public void operation() {
        //基础功能实现
    }
}
//装饰类
public class Decorator implements Component{
    private Component component;
    public Decorator(Component component){
        this.component=component;
    }
    @Override
    public void operation() {
        component.operation();
    }
}
//装饰类子类
public class ConcreateDecorator extends Decorator{
    public ConcreateDecorator(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        adddedBehavior();
    }

    private void adddedBehavior() {
        //TODO  新的业务逻辑
    }
}
 Component component=new ConcreteComponent();
 ConcreteDecorator concreateDecorator=new ConcreteDecorator(component);
 concreateDecorator.operation();
  • 优点
    (1)对于扩展一个对象的功能,装饰模式比继承更加灵活,不会导致类的个数急剧增加
    (2)可以通过一个动态的方式来扩展一个对象的功能
    (3)可以对一个对象进行多次装饰,通过不同的具体装饰类以及这些装饰类的排列组合
  • 缺点
    (1)代码量增加
    (2)不易理解

总结:Component来实现一个功能的基本实现,在装饰类Decorator中呢 我们去实现的功能就是调用Component的基本方法,再由继承Decorator类的ConcreteDecorator类在这个基本方法前后进行一些定制化操作

二,Android中的装饰模式应用

  • context类
    ContextWrapper为装饰类集成了context,具体实现startActivity方法在ContextImpl中

相关文章

网友评论

      本文标题:设计模式-装饰模式

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