装饰器模式

装饰器模式

适用场景

  • 在不改变classA的情况下,给classA动态增加/增强功能

实现方法

  • Decorator继承classA的接口,并依赖classA
public interface A {
    void callA();
}

public class AImpl implements A {
    ......
}

public class Decorator implements A {
    private A a = new AImpl();

    public void callA() {
        // do sth.
        a.callA();
        // do sth.
    }
}

实现例子

  • java io: FilterInputStream
public class DecoratorDemo {
    public static void main(String[] args) {
        try(InputStream in = new FileInputStream("a.txt")) {
                FilterInputStream filterInputStream = new DataInputStream(in);
                System.out.println(filterInputStream.read());
            }
    }
}

这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章