Decorator模式簡介
Decorator模式又名包裝器(Wrapper)
有時候
我們可以使用一種更為靈活的方法
以上的方法就是Decorator模式
Component為組件和裝飾的公共父類
ConcreteComponent是一個具體的組件類
Decorator是所有裝飾的公共父類
ConcreteDecoratorA和ConcreteDecoratorB是具體的裝飾
Java IO包中的Decorator模式
JDK提供的java
首先來看一段用來創建IO流的代碼
以下是代碼片段
try {
OutputStream out = new DataOutputStream(new FileOutputStream(
} catch (FileNotFoundException e) {
e
}
這段代碼對於使用過JAVA輸入輸出流的人來說再熟悉不過了
以下是代碼片段
try {
OutputStream out = new FileOutputStream(
out = new DataOutputStream(out);
} catch(FileNotFoundException e) {
e
}
由於FileOutputStream和DataOutputStream有公共的父類OutputStream
OutputStream是一個抽象類
以下是代碼片段
public abstract class OutputStream implements Closeable
public abstract void write(int b) throws IOException;
}
它定義了write(int b)的抽象方法
ByteArrayOutputStream
以下是代碼片段
public class ByteArrayOutputStream extends OutputStream {
protected byte buf[];
protected int count;
public ByteArrayOutputStream() {
this(
}
public ByteArrayOutputStream(int size) {
if (size 〈
throw new IllegalArgumentException(
}
buf = new byte[size];
}
public synchronized void write(int b) {
int newcount = count +
if (newcount 〉 buf
byte newbuf[] = new byte[Math
System
buf = newbuf;
}
buf[count] = (byte)b;
count = newcount;
}
}
它實現了OutputStream中的write(int b)方法
接著來看一下FilterOutputStream
以下是代碼片段
public class FilterOutputStream extends OutputStream {
protected OutputStream out;
public FilterOutputStream(OutputStream out) {
this
}
public void write(int b) throws IOException {
out
}
}
同樣
BufferedOutputStream 和 DataOutputStream是FilterOutputStream的兩個子類
以下是代碼片段
public class BufferedOutputStream extends FilterOutputStream {
private void flushBuffer() throws IOException {
if (count 〉
out
count =
}
}
public synchronized void write(int b) throws IOException {
if (count 〉= buf
flushBuffer();
}
buf[count++] = (byte)b;
}
}
這個類提供了一個緩存機制
下面
自己寫一個新的輸出流
了解了OutputStream及其子類的結構原理後
以下是代碼片段
import java
import java
import java
/**
* A new output stream
* and won
* @author Magic
*
*/
public class SkipSpaceOutputStream extends FilterOutputStream {
public SkipSpaceOutputStream(OutputStream out) {
super(out);
}
/**
* Rewrite the method in the parent class
* skip the space character
*/
public void write(int b) throws IOException{
if(b!=
super
}
}
}
它從FilterOutputStream繼承
以下是一個測試程序
以下是代碼片段
import java
import java
import java
import java
import java
import java
/**
* Test the SkipSpaceOutputStream
* @author Magic
*
*/
public class Test {
public static void main(String[] args){
byte[] buffer = new byte[
/**
* Create input stream from the standard input
*/
InputStream in = new BufferedInputStream(new DataInputStream(System
/**
* write to the standard output
*/
OutputStream out = new SkipSpaceOutputStream(new DataOutputStream(System
try {
System
int n = in
for(int i=
out
}
} catch (IOException e) {
e
}
}
}
執行以上測試程序
以下是引用片段
Please input your words:
a b c d e f
abcdef
總 結
在java
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27522.html