考虑以下课程,我将覆盖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
有人,请建议我一个合适的设计模式来解决这个问题。
答案 0 :(得分:2)
假设您希望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)
。