考虑下面的类,其中我覆盖了OutputStream
public class MyOutputStream extends java.io.OutputStream {
public String clientId = null;
public String fileId = null;
public String filelocation = null;
public DBClient clientobj = null;
public OuputStream out = null;
public MyOuputStream(String clientid, String fileid, String filelocation) {
this.clientid = clientid;
this.fileid = fileid;
this.filelocation = filelocation;
}
public void write(byte[] bytes) throws IOException {
out.write(bytes);
}
private DBClient getInstance(String clientid, String fileid) throws DBClientException {
return this.clientobj = DBClient.getInstance(clientid, fileid);
}
private OutputStream getOuputStream(DFSClient clientobj) throws Exception {
return this.out = clientobj.getOutputStream();
}
}
在上面的代码中,使用
MyOuputStream
编写的DBClient对象和OuputStream必须在写操作之前进行初始化有人,请给我建议一个合适的设计模式来解决这个问题。
最佳答案
假设您希望MyOutputStream
将所有输出转发到从OutputStream
对象检索的DBClient
,则要扩展FilterOutputStream
,因此您可以免费获得所有委托实现。
要使用它,必须将OutputStream
从DBClient
赋予FilterOutputStream
构造函数,因此需要以静态方法准备数据。
public class MyOutputStream extends FilterOutputStream {
private String clientId;
private String fileId;
private String fileLocation;
private DBClient clientobj;
public static MyOutputStream create(String clientId, String fileId, String fileLocation) {
DBClient clientobj = DBClient.getInstance(clientId, fileId);
return new MyOutputStream(clientId, fileId, fileLocation, clientobj);
}
private MyOutputStream(String clientId, String fileId, String fileLocation, DBClient clientobj) {
super(clientobj.getOutputStream());
this.clientId = clientId;
this.fileId = fileId;
this.fileLocation = fileLocation;
this.clientobj = clientobj;
}
}
现在,您不用写
new MyOuputStream(clientId, fileId, fileLocation)
,而是写MyOuputStream.create(clientId, fileId, fileLocation)
。关于java - 在类中初始化以下实例的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38780732/