2011-02-25 46 views
1

我有兩個對象CreateDocumentHeader和RetrieveDocumentHeader,它們具有非常相似的結構。我正在閱讀每個對象並填充一個DTO。我不想爲每個對象創建不同的方法。我如何編寫一個單一的方法來填充它們。這是兩個類。用於填充不同對象的常見方法類似結構

public class CreateDocumentHeaderType { 
    protected CreateAdminRecordType administrativeRecord; 
    protected CreateControlRecordType controlRecord; 
    public CreateAdminRecordType getAdministrativeRecord() { 
     return administrativeRecord; 
    } 
    public void setAdministrativeRecord(CreateAdminRecordType value) { 
     this.administrativeRecord = value; 
    } 
    public CreateControlRecordType getControlRecord() { 
     return controlRecord; 
    } 
    public void setControlRecord(CreateControlRecordType value) { 
     this.controlRecord = value; 
    } 
} 

public class RetrieveDocumentHeaderType { 
    protected RetrieveAdminRecordType administrativeRecord; 
    protected RetrieveControlRecordType controlRecord; 
    public RetrieveAdminRecordType getAdministrativeRecord() { 
     return administrativeRecord; 
    } 
    public void setAdministrativeRecord(RetrieveAdminRecordType value) { 
     this.administrativeRecord = value; 
    } 
    public RetrieveControlRecordType getControlRecord() { 
     return controlRecord; 
    } 
    public void setControlRecord(RetrieveControlRecordType value) { 
     this.controlRecord = value; 
    } 
} 

這兩個版本的AdminstrativeRecord和ControlRecord也有類似的結構。

+0

感謝您的回覆,我真的很抱歉,我錯過了一點。 CreateDocumentHeaderType和RetrieveDocumentHeaderType等是JAXB生成的文件,所以我想我不能改變它們來實現或擴展任何接口或類。我很抱歉這個錯過。 – Ravi 2011-02-25 06:04:23

回答

0

我想我錯過了一些東西。你認爲抽象的父類嗎?

0

我將創建一個接口來描述這兩個類尊重的合同。

public interface DocumentHeaderType { 
    public AdminRecordType getAdminRecord() ; 

    public ControlRecordType getControlRecord() ; 
} 

下一步是通過抽象類提供基本實現。

public abstract class AbstractDocumentHeaderType implements DocumentHeaderType { 
    private AdminRecordType adminRecord ; 
    private ControlRecordType controlRecord ; 

    public AdminRecordType getAdminRecord() { 
     return adminRecord ; 
    } 
    public ControlRecordType getControlRecord() { 
     return controlRecord ; 
    } 
    // setters ... 
} 

現在你只需要你CreateDocumentRecordHeaderType和RetrieveDocumentRecordHeaderType擴展抽象類。現在

public class CreateDocumentHeaderType extends AbstractDocumentHeaderType { 
    // we inherit the getters and setters, we are pretty much set 
} 

的地步,該方法來填充值

public void populateDocumentRequest(AbstractDocumentHeaderType holder) { 
    holder.setAdminRecord(...); 
    holder.setControlRecord(...) ; 
} 

希望這有助於。