使用依赖注入作为单例的替代方案
我一直都知道单例是“不好的”,但直到现在我从 C++ 转向 Java 后,我才决定找到解决它们的方法。通过阅读一些内容,我发现工厂或依赖注入都可以完成这项工作,但我想对此进行一些确认。
举个例子,我打算编写一个 AnimationCache 单例来存储 Map
。不同的类应该能够(基本上)在任何地方访问此类,以便它们可以轻松有效地加载动画。如果有一个非常简短的示例来说明使用 DI 的等效代码会是什么样子,那就太好了。
另外,Guice 对于非 Web 应用程序来说是一个很好的 DI 框架吗?我已经使用 Spring 进行 Web 开发,但我不太确定它是否适用于游戏。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Spring 和 Guice 会做得很好。我个人更喜欢 Guice 进行纯粹的依赖注入,但 Spring 提供了更多功能。
代码看起来像这样:
我个人更喜欢构造函数注入,但您也可以使用 setter 注入或字段注入。
但请注意,DI 的目的并不是拥有“简单的单例”。其主要目的是通过注入模拟依赖项(此处为模拟
AnimationCache
实例),使代码(此处为AnimationCacheClient
)轻松实现单元稳定。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:
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 mockAnimationCache
instance).使用Spring,DI非常简单。使用 @Autowired 注释,您甚至不需要额外的 xml 来连接事物或 setter 方法。类中需要访问以前是您的单例的成员即可。
这是一个很好的例子: http://www.developer.com/java/other/article.php/3756831/Java-Tip-Simplify-Spring-Apps-with-Autowired.htm
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
我最近在 Singleton 上“使用”了这个线程,它有多糟糕可能是(或不是)以及你可以采取什么措施来绕过它。非常值得一读。
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.