在我的课程中初始化以下实例的最佳方法是什么?

时间:2016-08-05 03:42:45

标签: java oop design-patterns

考虑以下课程,我将覆盖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

有人,请建议我一个合适的设计模式来解决这个问题。

1 个答案:

答案 0 :(得分:2)

假设您希望MyOutputStream将所有输出转发到从OutputStream对象检索到的DBClient,您希望扩展FilterOutputStream,以便获得所有委托实现免费。

要使用它,您必须将OutputStreamDBClient提供给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)