java – 对象与静态方法的设计
发布时间:2020-05-24 15:00:02 所属栏目:Java 来源:互联网
导读:如下图所示,有两种简单的方法可以使流式复印机(引入Apache Commons或类似软件).我应该去哪一个,为什么? public class StreamCopier {private int bufferSize;public StreamCopier() { this(4096);}public StreamCopier(int bufferSize) { thi
|
如下图所示,有两种简单的方法可以使流式复印机(引入Apache Commons或类似软件).我应该去哪一个,为什么? public class StreamCopier {
private int bufferSize;
public StreamCopier() {
this(4096);
}
public StreamCopier(int bufferSize) {
this.bufferSize = bufferSize;
}
public long copy(InputStream in,OutputStream out ) throws IOException{
byte[] buffer = new byte[bufferSize];
int bytesRead;
long totalBytes = 0;
while((bytesRead= in.read(buffer)) != -1) {
out.write(buffer,bytesRead);
totalBytes += bytesRead;
}
return totalBytes;
}
}
VS public class StreamCopier {
public static long copy(InputStream in,OutputStream out)
throws IOException {
return this.copy(in,out,4096);
}
public static long copy(InputStream in,OutputStream out,int bufferSize)
throws IOException {
byte[] buffer = new byte[bufferSize];
int bytesRead;
long totalBytes = 0;
while ((bytesRead= in.read(buffer)) != -1) {
out.write(buffer,bytesRead);
totalBytes += bytesRead;
}
return totalBytes;
}
}
解决方法我将使用非静态(实例)版本,并将其作为与setter的显式依赖关系提供给消费者:嘲笑它进行单元测试是微不足道的,所以对消费者的测试并不适用于实施; 编辑 在回答“有用的!”评论“这是如何帮助嘲笑”的时候,这是如何工作的: class ThingThatUsesStreamCopier {
// our copier instance. set in constructor,but might equally use
// a setter for this:
private StreamCopier copier;
public ThingThatUsesStreamCopier(StreamCopier copier) {
this.copier = copier;
}
public void makeCopy(Stream in,Stream out) {
// probably something a little less trivial...
copier.copy(in,out);
}
}
当我来测试ThingThatUsesStreamCopier时,我可以创建一个mock object版本的StreamCopier,并使用这个模拟实例化ThingThatUsesStreamCopier. 通过这样做,我完全控制了我的模拟行为,所以我的测试与StreamCopier的任何实际实现脱钩.我只是测试消费者,而不是消费者加消费. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
