使用Guice的GoF标准工厂模式

use*_*625 5 java guice factory-pattern

我之前使用标准工厂模式方法创建类的实例(实现特定接口)使用Factory类,该类具有"create"方法,该方法根据传递给它的参数返回正确的实例(下面给出的示例片段) ):

public class SimpleFactory {
    public static SimpleObjectInterface getSimpleObject(int data) {
         SimpleObjectInterface toReturn;
          switch(data) {
           case 1:
            toReturn = new OneSimpleObject();
           break;
          case 2:
            toReturn = new TwoSimpleObject();
          break;
          default:
             toReturn = new DefaultSimpleObject();    
          break;  
        }
        return toReturn;
      }
}
Run Code Online (Sandbox Code Playgroud)

现在我在我的项目中使用Guice进行依赖注入.我的问题是如何使用Guice实现上述功能?需要哪个实现实例是在运行时根据一些用户输入决定的.

我查看了Provider和@Named注释.但我不明白它究竟会对我有多大帮助.

The*_*111 3

一般来说,对于您想要一个注入大多数依赖项但仍然允许一些客户端提供的依赖项的工厂的问题,您可以使用辅助注入工厂。

然而,在你的情况下,这会导致你的工厂中出现条件逻辑,这可能并不理想(在 Guice 模块中明确不鼓励这样做)。

我认为对于您的情况, MapBinder将是理想的选择,并且您根本不需要工厂,因为您只是切换数据类型而不是真正构建任何东西。在您的模块中,您配置int(在您的情况下)键到 impls 的映射SimpleObjectInterface。然后在你的主运行时类中注入映射,当你需要一个简单对象的实例并且有 intdata可用时,你可以调用get(data)注入的映射。

我这台机器上没有 IDE,所以我无法测试代码,但从记忆中来看,它会如下所示:

在你的模块中:

public class MyModule extends AbstractModule {
  protected void configure() {
    MapBinder<Integer, SimpleObjectInterface> mapbinder
        = MapBinder.newMapBinder(binder(), Integer.class, SimpleObjectInterface.class);
    mapbinder.addBinding(1).toClass(OneSimpleObject.class);
    mapbinder.addBinding(2).toClass(TwoSimpleObject.class);
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的应用程序代码中:

@Inject
private Map<Integer, SimpleObjectInterface> simpleObjectMap;

...

void applicationCode() {
  ...
  Integer data = getData();
  SimpleObjectInterface simpleObject = simpleObjectMap.get(data);
  ...
}
Run Code Online (Sandbox Code Playgroud)

这里唯一的问题是你不能拥有 switch 语句中的“默认”绑定。不确定处理该问题的最佳方法,如果在尝试从地图绑定器实例化该对象后该对象仍然为空,也许您可​​以在应用程序代码中分配一个默认的 impl。或者您可以返回到带有条件逻辑的辅助注入,但如果唯一的依赖项是客户端提供的,那么它并不是真正的“辅助”注入。

另请参阅:Guice 能否根据参数自动创建不同类的实例?