java装饰模式模拟流_Java 装饰模式 io流
在Java IO流的API中,大量的使用了裝飾模式。
現在筆者來闡述一下裝飾模式。
裝飾模式的角色:
--抽象構件角色(Component): 給出一個抽象接口,以規范準備接收附加責任的對象。
--具體構件角色(Concrete Component):
定義一個將要接收附加責任的類。
--裝飾角色(Decorator): 持有一個構件(Component)對象的引用,并定義一個與抽象構件接口一致的接口。
--具體裝飾角色(Concrete Decorator):負責給構件對象"貼上"附加的責任。
======================================
裝飾模式和繼承之間的對比:
1)裝飾模式用于擴展特定對象的功能,而繼承則是寫死在類模板里面的。
2)對于一個給定的對象,同時可能有不同的裝飾對象,客戶端可以通過它的需要選擇合適的裝飾對象發送消息。而繼承則需要不停的定義新的子類,造成java類的數量急劇上升
3)裝飾模式更加靈活,繼承則相對比較死板。。
筆者現在用代碼來實現一下
package org.hl.decorator;
//抽象構件角色
public interface Component {
void doSomething();
}
package org.hl.decorator;
//具體的構件角色,相當于FileOutputStream(節點流)
public class ConcreteComponent implements Component {
@Override
public void doSomething() {
System.out.println("功能A");
}
}
package org.hl.decorator;
//裝飾角色,相當于FilterOutputStream(過濾流)
public class ConcreteDecorator extends ConcreteComponent {
private Component component;
public ConcreteDecorator(Component component) {
this.component = component;
}
@Override
public void doSomething() {
component.doSomething();
}
}
package org.hl.decorator;
//具體裝飾角色,相當于BufferedOutputStream
public class DecoratorA extends ConcreteDecorator {
public DecoratorA(Component component) {
super(component);
}
@Override
public void doSomething() {
super.doSomething();
this.doAnotherThing();
}
private void doAnotherThing() {
System.out.println("裝飾器提供的額外的功能A");
}
}
package org.hl.decorator;
public class DecoratorB extends ConcreteDecorator {
public DecoratorB(Component component) {
super(component);
}
@Override
public void doSomething() {
super.doSomething();
this.doAnotherThing();
}
private void doAnotherThing() {
System.out.println("裝飾器提供的額外的功能B");
}
}
我們再來寫個main 方法測試一下
package org.hl.decorator;
public class Client {
public static void main(String[] args) {
ConcreteComponent component = new DecoratorA(new DecoratorB(new ConcreteComponent()));
component.doSomething();
}
}
這樣的寫法是不是和 Java 的IO流API寫法類似呢
OutputStream outputStream1 = newBufferedOutputStream(newFileOutputStream("a.txt"));
附上一張圖片:
總結
以上是生活随笔為你收集整理的java装饰模式模拟流_Java 装饰模式 io流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 转xml 变成两根下划线_XS
- 下一篇: 超绝的收纳设计收纳设计方案