开发者

Using Dependency Injection as an alternative to Singletons

开发者 https://www.devze.com 2023-03-29 23:23 出处:网络
I\'ve always known Singletons to be \"bad\", but only now 开发者_Go百科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 eithe

I've always known Singletons to be "bad", but only now 开发者_Go百科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.

0

精彩评论

暂无评论...
验证码 换一张
取 消