学JAVA IO先学装饰模式

来源:互联网 发布:淘宝开店诈骗 编辑:程序博客网 时间:2024/06/10 08:07
     想要搞懂JAVA I/O,需要先学习装饰模式,为什么这么说,JAVA I/O中数据在具体目标(文件、外设、网络)与程序之间进行流进流出时,涉及到节点流与过滤流。
    当数据由具体目标,比如文件,流向程序时,会经过直接与文件打交道的节点流,如FileInputStream,然而为了在文件流进到程序的过程中,让它具备先读入到内存的缓冲区,增加一个缓冲的功能,此时就会用到一个过滤流,BufferedInputStream,要想让数据读入到程序时,可以读取文件中的数据类型,那么在流的过程之中,我们还可以为流加入另外一个过滤流,DataInputStream,使之具备读具体数据类型的功能。这一过程的简写:
文件——节点流——过滤流——过滤流——程序。从这一过程,说明功能是在动态的变化的。这即是一个装饰模式的典型示例。
    装饰模式究竟是干啥的呢?
    就是一种以透明方式扩展对象功能的模式,是一种动态的扩展,可以代替继承的静态扩展。
    为什么继承是静态扩展呢?
    因为继承的扩展是建立在增加子类的基础上的。
    而装饰模式,则是动态的组合有限类的功能,实现对象功能的动态扩展。
    下面是这一模式的示例:

package com.javase.decorator2;

public interface Component {
    public void doSomething();
}
package com.javase.decorator2;


public class ConcreteComponent implements Component {

    @Override
    public void doSomething() {
        System.out.println("具体构件角色功能");
    }

}
package com.javase.decorator2;

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

    @Override
    public void doSomething() {
        this.component.doSomething();       
    }
}

package com.javase.decorator2;

public class ConcreteDecorator1 extends Decorator {

    public ConcreteDecorator1(Component component) {
        super(component);
    }
   
    @Override
    public void doSomething() {
        super.doSomething();
        this.doAnotherThing();
    }
   
    private void doAnotherThing(){
        System.out.println("具体装饰角色功能B");
    }

}

package com.javase.decorator2;


public class ConcreteDecorator2 extends Decorator {

    public ConcreteDecorator2(Component component) {
        super(component);
    }
   
    @Override
    public void doSomething() {
        super.doSomething();
        this.doAnotherThing();
    }
   
    private void doAnotherThing(){
        System.out.println("具体装饰角色功能C");
    }

}

package com.javase.decorator2;

public class Client {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        //未装饰
        component.doSomething();
        System.out.println("----------------------");
        //使用装饰1
        Component component1 = new ConcreteDecorator1(new ConcreteComponent());
        component1.doSomething();
        System.out.println("========================");
        //使用装饰1与装饰2
        Component component2 = new ConcreteDecorator2(new ConcreteDecorator1(new ConcreteComponent()));
        component2.doSomething();
    }
}