[英]Meaning of “object is in inconsistent state”
我遇到過多次以特定方式編碼對象可能導致它處於不一致狀態。 一個例子就是這個問題 。
從答案:使用裝飾器模式構造對象是不好的,因為它使對象處於不一致狀態。
任何人都可以通過一個例子向我解釋一下,處於不一致狀態的對象究竟意味着什么?
考慮下面的類,它是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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.