当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 结构型模式之装饰模式

结构型模式之装饰模式

2018年12月10日  | 移动技术网IT编程  | 我要评论

装饰模式(decorator pattern)是一种比较常见的模式。

定义:

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

装饰模式类图如下所示。

 

装饰模式有以下4个角色。

  • 抽象构件(component)角色:用于规范需要装饰的对象(原始对象)。
  • 具体构件(concretecomponent)角色:实现抽象构件接口,定义一个需要装饰的原始类。
  • 装饰(decorator)角色:持有一个构件对象的实例,并定义一个与抽象构件接口一致的接口,
  • 具体装饰角色:负责对构件对象进行装饰。

component.java

public interface component {
    public void operation();
}

concretecomponent.java

public class concretecomponent implements component {
    @override
    public void operation() {
        system.out.println("业务代码");
    }
}

decorator.java

public abstract class decorator implements component {
    private component component = null;
    public decorator(component component) {
        this.component = component;
    }
    @override
    public void operation() {
        this.component.operation();
    }
}

concretedecorator.java

public class concretedecorator extends decorator {
    public concretedecorator(component component) {
        super(component);
    }
    // 定义自己的方法
    public void selfmethod() {
        system.out.println("修饰");
    }
    // 重写operation
    @override
    public void operation() {
        this.selfmethod();
        super.operation();
    }
}

client.java

public class client {
    public static void main(string[] args) {
        component component = new concretecomponent();
        // 进行装饰
        component = new concretedecorator(component);
        component.operation();
    }
}

优点:

  • 装饰类和被装饰类可以独立发展,而不会相互耦合。即component类无须知道decorator类,decorator类是从外部来扩展component类的功能,而decorator也不用知道具体的构件。
  • 装饰模式是继承关系的一个替代方案。装饰类decorator,不管装饰多少层,返回的对象还是component.
  • 装饰模式可以动态地扩展一个实现类的功能。

缺点:

  • 多层的装饰是比较复杂的。

应用场景:

  • 需要扩展一个类的功能,或给一个类增加附加功能。
  • 需要动态地给一个对象增加功能,这些功能可以再动态地撤销。
  • 需要为一批类进行改装或加装功能。

装饰模式是对继承的有力补充。单纯使用继承时,在一些情况下就会增加很多子类,而且灵活性较差,维护也不容易。装饰模式可以替代继承,解决类膨胀的问题,如java基础类库中的输入输出流相关的类大量使用了装饰模式。

摘自:

青岛东合信息技术有限公司 . 设计模式(java版) .  电子工业出版社,2012,78-80.

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网