Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 485
Mitch Avatar asked Aug 22 '11 08:08

Mitch


2 Answers

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).

like image 197
JB Nizet Avatar answered Oct 04 '22 22:10

JB Nizet


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

like image 32
mort Avatar answered Oct 04 '22 20:10

mort