java装饰模式模拟流_Java 装饰模式 io流
在Java IO流的API中,大量的使用了裝飾模式。
現(xiàn)在筆者來(lái)闡述一下裝飾模式。
裝飾模式的角色:
--抽象構(gòu)件角色(Component): 給出一個(gè)抽象接口,以規(guī)范準(zhǔn)備接收附加責(zé)任的對(duì)象。
--具體構(gòu)件角色(Concrete Component):
定義一個(gè)將要接收附加責(zé)任的類(lèi)。
--裝飾角色(Decorator): 持有一個(gè)構(gòu)件(Component)對(duì)象的引用,并定義一個(gè)與抽象構(gòu)件接口一致的接口。
--具體裝飾角色(Concrete Decorator):負(fù)責(zé)給構(gòu)件對(duì)象"貼上"附加的責(zé)任。
======================================
裝飾模式和繼承之間的對(duì)比:
1)裝飾模式用于擴(kuò)展特定對(duì)象的功能,而繼承則是寫(xiě)死在類(lèi)模板里面的。
2)對(duì)于一個(gè)給定的對(duì)象,同時(shí)可能有不同的裝飾對(duì)象,客戶端可以通過(guò)它的需要選擇合適的裝飾對(duì)象發(fā)送消息。而繼承則需要不停的定義新的子類(lèi),造成java類(lèi)的數(shù)量急劇上升
3)裝飾模式更加靈活,繼承則相對(duì)比較死板。。
筆者現(xiàn)在用代碼來(lái)實(shí)現(xiàn)一下
package org.hl.decorator;
//抽象構(gòu)件角色
public interface Component {
void doSomething();
}
package org.hl.decorator;
//具體的構(gòu)件角色,相當(dāng)于FileOutputStream(節(jié)點(diǎn)流)
public class ConcreteComponent implements Component {
@Override
public void doSomething() {
System.out.println("功能A");
}
}
package org.hl.decorator;
//裝飾角色,相當(dāng)于FilterOutputStream(過(guò)濾流)
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;
//具體裝飾角色,相當(dāng)于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");
}
}
我們?cè)賮?lái)寫(xiě)個(gè)main 方法測(cè)試一下
package org.hl.decorator;
public class Client {
public static void main(String[] args) {
ConcreteComponent component = new DecoratorA(new DecoratorB(new ConcreteComponent()));
component.doSomething();
}
}
這樣的寫(xiě)法是不是和 Java 的IO流API寫(xiě)法類(lèi)似呢
OutputStream outputStream1 = newBufferedOutputStream(newFileOutputStream("a.txt"));
附上一張圖片:
總結(jié)
以上是生活随笔為你收集整理的java装饰模式模拟流_Java 装饰模式 io流的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java 转xml 变成两根下划线_XS
- 下一篇: java美元兑换,(Java实现) 美元