1 package cz.cuni.amis.pogamut.base.factory.guice; 2 3 import com.google.inject.Guice; 4 import com.google.inject.Injector; 5 6 import cz.cuni.amis.utils.NullCheck; 7 8 /** 9 * Abstract Guice-based factory that uses {@link GuiceAgentModule} for the bindings. 10 * <p><p> 11 * It simply wraps the Guice's {@link Injector}, which it creates based on the passed module. 12 * <p><p> 13 * The module can be reset using {@link AbstractGuiceAgentFactory#setAgentModule(GuiceAgentModule)}. 14 * 15 * @author Jimmy 16 */ 17 public abstract class AbstractGuiceAgentFactory { 18 19 /** 20 * Custom module used to initialize the {@link AbstractGuiceAgentFactory#injector}. 21 */ 22 private GuiceAgentModule module; 23 24 /** 25 * Injector created using {@link AbstractGuiceAgentFactory#module}. Lazy-initialized inside {@link AbstractGuiceAgentFactory#getInjector()}. 26 */ 27 private Injector injector; 28 29 /** 30 * Parameter-less constructor that can be utilized in situations when you have to set the {@link GuiceAgentModule} 31 * later. (DO NOT FORGET TO DO IT VIA {@link AbstractGuiceAgentFactory#setAgentModule(GuiceAgentModule)} :-) 32 */ 33 public AbstractGuiceAgentFactory() { 34 } 35 36 /** 37 * Creates a Guice-based factory that will use {@link Injector} created using the 'module'. 38 * 39 * @param module module that configures bindings between classes, may be null (specify module later using {@link AbstractGuiceAgentFactory#setAgentModule(GuiceAgentModule)}) 40 */ 41 public AbstractGuiceAgentFactory(GuiceAgentModule module) { 42 this.module = module; 43 } 44 45 /** 46 * Returns the module that the factory is working with. Can be utilized to slip run-time dependencies 47 * into the module. 48 * 49 * @return factory module 50 */ 51 protected GuiceAgentModule getAgentModule() { 52 return module; 53 } 54 55 /** 56 * Sets new agent module into the factory, it invalidates the {@link AbstractGuiceAgentFactory#injector} 57 * so the new one is created when {@link AbstractGuiceAgentFactory#getInjector()} is called. 58 * 59 * @param module new module 60 */ 61 protected synchronized void setAgentModule(GuiceAgentModule module) { 62 if (module == this.module) return; 63 this.module = module; 64 this.injector = null; 65 } 66 67 /** 68 * Injector that should be used to instantiates new objects according to the module. 69 * <p><p> 70 * Lazy-initialized using {@link GuiceAgentFactory#getAgentModule()}. 71 * 72 * @return injector configured by {@link GuiceAgentFactory#getAgentModule()} 73 */ 74 protected synchronized Injector getInjector() { 75 if (this.injector == null) { 76 GuiceAgentModule module = getAgentModule(); 77 NullCheck.check(module, "getAgentModule()"); 78 this.injector = Guice.createInjector(module); 79 NullCheck.check(this.injector, "Guice.createInjector(getAgentModule())"); 80 } 81 return this.injector; 82 } 83 84 }