1
我已經在代碼中寫了下面GenericDAO如下通用DAO和類型的業務對象 - 的方式來減少代碼
abstract public class DAO <T extends AbstractBusinessObject> {
// CRUD: create, read, update, delete
public abstract T create(Class<T> abObj);
public abstract T read();
public abstract void update(T abObj);
public abstract void delete(T abObj);
但occasionaly當我實現自定義的DAO(如DAOinMemory)和它的方法,如create
我必須 寫下面的代碼:
public T create(Class<T> abstractObjectType) {
IDGenerator IDGenerator = IDGenerator.getInstance();
if (BusinessEntityFirst.class.isAssignableFrom(abstractObjectType)) {
BigInteger id = IDGenerator.getID();
BusinessEntityFirst bef = new BusinessEntityFirst(id);
return (T) bef;
}
if (BusinessEntitySecond.class.isAssignableFrom(abstractObjectType)) {
BigInteger id = IDGenerator.getID();
BusinessEntitySecond bes = new BusinessEntitySecond(id);
return (T) bes;
}
if (BusinessEntityThird.class.isAssignableFrom(abstractObjectType)) {
BigInteger id = IDGenerator.getID();
BusinessEntityThird bet = new BusinessEntityThird(id);
return (T) bet;
}
if (abstractObjectType == null) {
throw new NullPointerException("Can't create instance for:" + abstractObjectType);
}
return null;
}
我看到create
- 方法實施的一些地方看起來像麪條代碼(三個IF-CO與.isAssignableFrom
方法),我無法做任何事情來克服它。你能否建議一些如何爲這部分代碼編寫一段代碼以擺脫Spaghetti代碼?
我會爲業務類製作單獨的DAO類(相應地鍵入)。正如你注意到你自己一樣,你試圖將它們全部塞進一個班級,你完全沒有辦法。 – Kayaman
您可以在類中擴展抽象類,並說C,然後擴展類C的類。然後在類C中定義該創建方法,並在擴展類中使用它們。這聽起來不錯嗎? –