簡體   English   中英

猜猜我如何根據String id提供不同的子類實例

[英]Guice how can I provide different subclasses instance depending on String id

我有一個要用Guice實現的Factory類用例,但不確定如何使用。 我有一個名為Action的抽象類,它表示用戶可以在我的應用程序上執行的不同類型的操作。 每個動作都是動作類的子類,並且每個動作還具有String類型的標識。 因為動作是沉重的對象,所以我不想立即實例化所有動作,所以我提供了一個Factory來實例化每個動作,具體取決於客戶要求的ID。

工廠界面如下所示:

public interface ActionFactory {

    Action getActionByID(String id);

}

我們對這個Factory的實現使用HashMap來維護String實例與將提供具體Action實例的所謂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的新手,所以也許這是我在文檔中找不到的非常常見的情況,如果出現這種情況,我表示歉意。 任何幫助將不勝感激。 問候丹尼爾

您想使用Multibindings擴展,特別是MapBinder 您可能希望您的ActionInstantiator類型實現Provider<Action> 然后,您可以執行以下操作:

MapBinder<String, Action> mapbinder
     = MapBinder.newMapBinder(binder(), String.class, Action.class);
mapbinder.addBinding("actionAAA", ActionAAAInstantiator.class);
// ...

然后,您可以在所需的位置插入Map<String, Provider<Action>> 您還可以將內容注入到ActionInstantiator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM