设计模式---装饰器模式

  本篇来讲讲装饰器模式,装饰器也是比较常见的模式,在java的IO中广泛应用。

1、定义

  装饰器模式是动态地将责任附加到对象上。若要扩展功能,装饰器提供了比继承更有弹性的替代方案。

  以上的定义比较拗口,通俗的讲装饰器是对原有的方法的增强,跟后续要讲的代理模式很像,区别在于代理模式是屏蔽了代理类,装饰器模式注重附加额外的功能。

2、UML

 

Component:一个接口或者抽象类。

ConcreteComponent:具体的组件实现类。

Decorator:装饰器,通常是抽象类。每个装饰器都有一个组件,是对Component的引用。

ConcreteDecoratorA:具体的装饰器的实现类,继承自装饰器。

ConcreteDecoratorB:具体的装饰器的实现类,继承自装饰器。

 3、案例

   首先新建抽象类component

package com.design_pattern.decorator;

public abstract class Component {
    abstract void show();
}

  接着建实现component的子类

package com.design_pattern.decorator;

public class ConcreteComponent extends Component {
    @Override
    void show() {
        System.out.println("this is ConcreteComponent");
    }
}

  再新建装饰类Decorator

package com.design_pattern.decorator;

public abstract class Decorator extends Component{

    private Component component;

    public Decorator(Component component){
        this.component = component;
    }

    public void decoratorShow(){
        component.show();
    }

}

  实现装饰类ConcreteDecoratorA

package com.design_pattern.decorator;

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

    @Override
    void show() {
        setUpdate();
        super.decoratorShow();
    }

    void setUpdate(){
        System.out.println("update");
    }
}

  以上就实现了装饰器模式,试试效果吧

package com.design_pattern.decorator;

public class Client {
    public static void main(String[] args) {
        ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(new ConcreteComponent());
        concreteDecoratorA.show();
    }
}

 4、实践

  装饰器模式在java IO类中实现较多,比如在抽象类inputStream,实现的子类有FileInputStream、ByteArrayInputStream等,而FilterInputStream作为装饰类,BufferedInputStream就是具体的实现。

  inputStream中的read

   filterInputStream中的read方法调用的是inputStream的read方法

   BufferedInputStream中实现的read方法是调用fill方法,fill方法中增加了缓存功能,最终再调用inputStream的read方法

 

 

 以上就是本篇装饰器模式的全部内容了。

猜你喜欢

转载自www.cnblogs.com/sgx2019/p/11333131.html