将close()视为流对象的非核心功能是有意义的。这就是为什么将此方法放在interface Closeable中的原因。一个证据是,class ByteArrayInputStream不需要close()操作。
public abstract class InputStream implements Closeable {}
public abstract class OutputStream implements Closeable, Flushable {}基于上述定义,我观察到interface Closeable不应该由abstract class InputStream/OutputStream实现;它必须留给具体的子类(如class FileInputStream)来实现。

你认为我的理解是正确的吗?
发布于 2014-12-20 16:30:24
只有我的两分钱。这个答案的目的是给出一些想法和吸引更多的答案,而不是试图听起来像决定性的,甚至提供信息。
的操作的基础。
与你的观点相反,我认为不需要关闭的溪流是少数,而不是多数。
坦率地说,
看来是这样的。对于不需要显式关闭的流,要求它提供不做任何操作的微不足道的close()方法是无害的。
类似的观察可以在C#语言中找到,在那里通常可以看到亚型 IDisposable的接口。
是。如果不将其放在接口上,或者将其分配给第二个Closeable接口,则会造成非常大的危害。
在下面的第一个代码片段中,假设InputStream不包含close()方法。下面是代码的样子:
public void parseAndCloseStream(InputStream strm) throws IOException
{
if (strm == null) { /* ... to avoid NPE inside finally */ }
try
{
// read from stream
}
finally
{
if (strm instanceof Closeable)
{
Closeable c = (Closeable)strm;
c.close();
}
}
}换句话说,由于省略意味着“并非每个InputStream都是关闭的”,因此任何InputStream实例的任何使用者现在都有额外的责任来检查实例是否确实是可关闭的。
然后,try-with模式还需要更多的代码,因为您不能在那里使用InputStream,除非您可以将其转换为可关闭的代码。
不是的。
具体而言,接口隔离原则不要求:
https://softwareengineering.stackexchange.com/questions/266988
复制相似问题