2011-09-13 10 views
2

私はGuiceで実装したいファクトリクラスのユースケースを持っていますが、その方法はわかりません。 私は、ユーザーが私のアプリで実行できる別の種類のアクションを表すアクションという抽象クラスを持っています。 アクションのそれぞれはActionクラスのサブクラスであり、それぞれにはString型の識別情報もあります。 アクションは重いオブジェクトなので、一度にインスタンス化したくないので、クライアントが要求するIDに応じてインスタンスを生成するためのファクトリを提供します。この工場の当社の実装は、Stringインスタンスと具体的なアクションのインスタンスを提供していますいわゆるActionInstantiatorとの関係を維持するために、HashMapを使用していますguice String idに応じて異なるサブクラスのインスタンスを提供する方法

public interface ActionFactory { 

    Action getActionByID(String id); 

} 

工場インタフェースは次のようになります。だから、

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 action=ActionFactoryImpl.instance().getActionByID(actionId); 

本の 実装は次のようになります。

私は、ある種のアノテーションインジェクションが同様のことをする可能性があることを知りましたが、私の場合、それはうまくいかないと思います。なぜなら、ユーザーが実行時にrequieresするインスタンスしか知っていないからです。コード上に

私はGuiceを初めて使っています。多分これは非常に一般的なことですが、私はドキュメントで見つけられませんでした。 助けていただければ幸いです。 よろしく ダニエル

答えて

4

あなたはMultibindings拡張子を使用したい、特にMapBinderActionInstantiatorタイプにProvider<Action>を実装することをお勧めします。次に、あなたはできる:

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

あなたがしたい場合は、Map<String, Provider<Action>>を注入することができます。また、ActionInstantiatorに物を注入することもできます。

+0

答えてくれてありがとうColin、私はそれがGuice 3.0を使って私のサーバーに向ける解決策になると思います。しかし、私はGWTクライアント側でGin 1.5で実装できる解決策が必要です。 –

+0

@Daniel: 'bind(ActionFactory.class).to(ActionFactoryImpl.class)'? – ColinD

関連する問題