學JAVA IO先學裝飾模式

     想要搞懂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();
  
發佈了35 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章