我有一個工廠類用例,我想用Guice實現,但不知道如何實現。 我有一個名爲Action的抽象類,它表示用戶可以在我的應用上執行的不同類型的操作。 每個Actions都是Action類的子類,並且每個Action也都有一個String類型的標識。 由於動作是沉重的對象,我不希望立刻全部實例化,所以我提供了一個工廠來根據客戶請求的ID實例化它們中的每一個。Guice我如何根據字符串id提供不同的子類實例
工廠接口的樣子:
public interface ActionFactory {
Action getActionByID(String id);
}
我們這個廠實現使用一個HashMap維持String實例和所謂的ActionInstantiator將提供具體的操作實例之間的關係。 的這個實施樣子:
public class ActionFactoryImpl implements ActionFactory {
private HashMap<String, ActionInstantiator> actions;
private static ActionFactoryImpl instance;
protected ActionFactoryImpl(){
this.actions=new HashMap<String, ActionInstantiator>();
this.buildActionRelationships();
}
public static ActionFactoryImpl instance(){
if(instance==null)
instance=new ActionFactoryImpl();
return instance;
}
public Action getActionByID(String id){
ActionInstantiator ai = this.actions.get(id);
if (ai == null) {
String errMessage="Error. No action with the given ID:"+id;
MessageBox.alert("Error", errMessage, null);
throw new RuntimeException(errMessage);
}
return ai.getAction();
}
protected void buildActionRelationships(){
this.actions.put("actionAAA",new ActionAAAInstantiator());
this.actions.put("actionBBB",new ActionBBBInstantiator());
.....
.....
}
}
所以有些客戶端可以使用這個工廠,並希望ActionAAA實例類調用它是這樣的:
Action action=ActionFactoryImpl.instance().getActionByID(actionId);
凡actionId在從數據庫運行時獲得的。
我發現某種類型的註釋注入可以做類似的事情,但在我的情況下,我認爲這是行不通的,因爲我只知道用戶在運行時需要的實例,所以我不能註釋在代碼上。
我是新來的Guice,所以也許這是非常常見的東西,我無法在文檔中找到,我的appologies如果是這樣的話。 任何幫助將不勝感激。 Registers Daniel
感謝您的回答科林,我認爲這可能是一個使用Guice 3.0爲我的服務器的解決方案。但我需要一個我可以在GWT客戶端使用Gin 1.5實現的解決方案。 –
@Daniel:'bind(ActionFactory.class).to(ActionFactoryImpl.class)'? – ColinD