[英]Is it considered bad practice/design to create 10s/100s of Guice Injectors?
Consider a hypothetical application: 考虑一个假设的应用程序:
Question: Assuming that for some reason the problem described above cannot be accomplished by using run of the mill design patterns like Factory, Builder, Creator etc: 问题:假设由于某种原因,无法通过使用工厂,构建器,创建者等工厂设计模式来解决上述问题:
new
) 可读性(与使用普通的旧Java new
) At the level of abstraction you described, that sounds like a reasonable solution, and conducive to some good design patterns (like loose coupling and instance immutability). 在您描述的抽象级别上,这听起来像是一个合理的解决方案,并且有助于某些良好的设计模式(例如,松散耦合和实例不变性)。 To the best of my knowledge Guice will not pose any greater threat of memory leaks or other performance problems than any comparable solution for those complex needs—just keep an eye on which references you keep so the GC can do its job. 据我所知,Guice不会比针对那些复杂需求的任何同类解决方案带来更大的内存泄漏或其他性能问题的威胁-只需留意所保留的引用,GC就可以完成工作。
To that point you may want to be careful about creating singleton objects in Guice, though, if you rely on them being garbage collected. 到那时,如果您依赖于对对象进行垃圾收集,则可能要在Guice中创建单例对象时要小心。 Objects declared as @Singleton
(or asEagerSingleton
or toInstance
) cannot be garbage-collected as long as the Injector is reachable, because the Injector is obligated to return the exact same instance if it is ever asked for again. 声明为对象@Singleton
(或asEagerSingleton
或toInstance
)不能作为垃圾回收,只要注射器可达,因为注射器有义务返回完全相同的情况下,如果它是不断询问一次。 In desktop VMs it may be cheaper to get multiple instances of a stateless object so the GC can collect them all, rather than declaring the object as a singleton that can never be collected. 在台式机VM中,获取无状态对象的多个实例可能会比较便宜,以便GC可以收集所有实例,而不是将对象声明为永远无法收集的单个实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.