2014-08-28 54 views
2

我遇到過多次以特定方式編碼對象可能導致其處於不一致狀態的情況。一個例子是這個question「對象處於不一致狀態」的含義

從答案:使用裝飾模式來構造對象是不好的,因爲它使對象處於不一致的狀態。

任何人都可以請我解釋一下,舉個例子,一個處於不一致狀態的對象究竟意味着什麼?

回答

2

請考慮下面的類,它是InputStream的裝飾類。這裏close()方法保持未實現。 現在,如果我創建了這個類的一個對象,並且調用close(),我的假設是該流已關閉,但實際上,由於裝飾器類中未完成實現的方法close()而未關閉。

public class UnClosableDecorator extends InputStream { 

    private final InputStream inputStream; 

    public UnClosableDecorator(InputStream inputStream) { 
     this.inputStream = inputStream; 
    } 

    @Override 
    public int read() throws IOException { 
     return inputStream.read(); 
    } 

    @Override 
    public int read(byte[] b) throws IOException { 
     return inputStream.read(b); 
    } 

    @Override 
    public int read(byte[] b, int off, int len) throws IOException { 
     return inputStream.read(b, off, len); 
    } 

    @Override 
    public long skip(long n) throws IOException { 
     return inputStream.skip(n); 
    } 

    @Override 
    public int available() throws IOException { 
     return inputStream.available(); 
    } 

    @Override 
    public synchronized void mark(int readlimit) { 
     inputStream.mark(readlimit); 
    } 

    @Override 
    public synchronized void reset() throws IOException { 
     inputStream.reset(); 
    } 

    @Override 
    public boolean markSupported() { 
     return inputStream.markSupported(); 
    } 

    @Override 
    public void close() throws IOException { 
     //do nothing 
    } 
} 
相關問題