我曾多次遇到过,以特定方式对对象进行编码可能会导致其处于不一致的状态。一个例子是这样的question https://stackoverflow.com/questions/4768349/builder-vs-decorator-pattern.
从答案来看:使用装饰器模式来构造对象是不好的,因为它会使对象处于不一致的状态。
谁能用一个例子向我解释一下,处于不一致状态的对象真正意味着什么?
考虑下面的类,它是装饰器类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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)