Custom Guice Scope, or a better approach?

后端 未结 4 1481
迷失自我
迷失自我 2020-12-13 14:55

Here\'s my problem:

It\'s first important to know that I\'m writing a simulation. This is a standalone application, and is single-threaded. I have essentially two

4条回答
  •  我在风中等你
    2020-12-13 15:29

    Have you considered using a provider? It would be easy to write one that meets your requirements, e.g.:

    import com.google.inject.Provider
    
    class RootObjectProvider implements Provider {
    
        ...
    
        @Override
        RootObject get() {
            ClassD d = new ClassD( .... );
            ClassB b = new ClassB( ..., d, ...);
            ClassC c = new ClassC( ..., d, ...); // Note that b and c share d.
            return new RootObject(b, c, ...);
        }
    }
    

    You can use the provider two ways:

    1. Bind it as a provider with either the @Provides interface or the .toProvider() binding decoration.
    2. Inject the provider directly and invoke it to create RootObject instances as needed.

    Hope that this helps.

提交回复
热议问题