Using dependency injection as an alternative to singleton

I always knew that Singletons would be “bad,” but only now that I switched to Java with C ++ did I decide to find a way around them. From a small number of readings, I found that either Factories or Dependency Injection could do the job, but I would like confirmation.

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

Also, is Guice a good framework for DI with non-web applications? I used Spring for web development, but I'm not sure what will work in games.

+6
source share
3 answers

Spring, and Guise will be all right. I personally prefer Guice for a clean dependency injection, but Spring offers a lot more.

The code will look something 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 personally prefer constructor injection, but you can also use installer injection or field injection.

Note that the purpose of DI is not to have “simple singletones”. Its main purpose is to make the code ( AnimationCacheClient here) easily unit-estable, being able to introduce mock dependencies (here, the AnimationCache layout).

+5
source

Using Spring, DI is very simple. Using the @Autowired annotation, you don’t even need additional xml to connect or the setter method. A member in the class who needs access to the one that was your single before that will do.

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

+1
source

Source: https://habr.com/ru/post/895567/


All Articles