简体   繁体   中英

Using Dependency Injection as an alternative to Singletons

I've always known Singletons to be "bad", but only now that I've made the move to Java from C++ have I decided to find a way around them. From a bit of reading, I've found that either Factories or Dependency Injection could possibly do the job, but I'd like some confirmation on this.

As an example, I was about to write a AnimationCache singleton that would store a Map<String, Animation> . Different classes should be able to have access to this class (basically) anywhere so that they can easily and efficiently load Animations. A very brief example of what the equivalent code would look like using DI would be great.

Also, is Guice a good framework for DI with non-web apps? I have used Spring for web development, but I'm not so sure that'd work for games.

Spring and Guice will do fine. I personnally prefer Guice for pure dependency injection, but Spring offers much more.

The code would just look like this:

public class AnimationCacheClient {

    private AnimationCache cache;

    @Autowired // for Spring, or
    @Inject // for Guice (but I think Spring also supports it now)
    public AnimationCacheClient(AnimationCache cache) {
        this.cache = cache;
    }

    // ...
}

I personnally prefer constructor injection, but you might also use setter injection or field injection.

Note that the purpose of DI is not to have "easy singletons", though. Its main purpose is to make the code (of AnimationCacheClient , here) easily unit-estable, by being able to inject mock dependencies (here, a mock AnimationCache instance).

Using Spring, DI is very simple. Using the @Autowired annotation, you don't even need additional xml to wire things up or a setter method. A member in the class that needs access to the one that has been your singleton before will do.

Here is a good example: http://www.developer.com/java/other/article.php/3756831/Java-Tip-Simplify-Spring-Apps-with-Autowired.htm

I recently 'withnessed' this thread on Singleton and how bad it might be (or not) and what you can do to bypass it. Well worth the read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM