JAVA 设计模式 装饰者模式

用途


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

 

装饰者模式是一种结构式模式

 


结构
图-装饰者模式结构图

 

Component : 定义一个对象接口,可以给这些对象动态地添加职责。
interface Component {
    public void operation();
}
ConcreteComponent : 实现 Component 定义的接口。
class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("初始行为");
    }
}
Decorator : 装饰抽象类,继承了 Component, 从外类来扩展 Component 类的功能,但对于 Component 来说,是无需知道 Decorator 的存在的。
class Decorator implements Component {
    // 持有一个 Component 对象,和 Component 形成聚合关系
    protected Component component;
    
    // 传入要进一步修饰的对象
    public Decorator(Component component) {
        this.component = component;
    }
    
    @Override
    // 调用要修饰对象的原方法
    public void operation() {
        component.operation();
    }
}
ConcreteDecorator : 具体的装饰对象,起到给 Component 添加职责的功能。
class ConcreteDecoratorA extends Decorator {
    private String addedState = "新属性1";
    
    public ConcreteDecoratorA(Component component) {
        super(component);
    }
    
    public void operation() {
        super.operation();
        System.out.println("添加属性: " + addedState);
    }
}

class ConcreteDecoratorB extends Decorator {
    public ConcreteDecoratorB(Component component) {
        super(component);
    }

    public void operation() {
        super.operation();
        AddedBehavior();
    }
    
    public void AddedBehavior() {
        System.out.println("添加行为");
    }
}

测试代码

public class DecoratorPattern {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        component.operation();
        
        System.out.println("======================================");
        Decorator decoratorA = new ConcreteDecoratorA(component);
        decoratorA.operation();
        
        System.out.println("======================================");
        Decorator decoratorB = new ConcreteDecoratorB(decoratorA);
        decoratorB.operation();
    }
}

运行结果

初始行为
======================================
初始行为
添加属性: 新属性1
======================================
初始行为
添加属性: 新属性1
添加行为

 

应用场景
1、需要动态的、透明的为一个对象添加职责,即不影响其他对象。

2、需要动态的给一个对象添加功能,这些功能可以再动态的撤销。

3、需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实。

4、当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。


要点

1、装饰对象和真实对象有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互。

2、装饰对象包含一个真实对象的引用(reference)。

3、装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。

4、装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。

 

 

 

推荐

本文属于 JAVA设计模式系列



参考资料

《大话设计模式》

《HeadFirst设计模式》 

 

posted @ 2015-01-15 15:41  静默虚空  阅读(2601)  评论(2编辑  收藏  举报