[英]Did Joshua Bloch say not to use singleton with underlying resources?
I have been reading Joshua Bloch's Effective Java book.我一直在阅读 Joshua Bloch 的Effective Java书。 In item #5, he seems to say not to use a singleton or static utility class to implement a class that depends on one or more underlying resources, and do not have the class create these resources directly, use dependency injection.
In item #5, he seems to say not to use a singleton or static utility class to implement a class that depends on one or more underlying resources, and do not have the class create these resources directly, use dependency injection.
I would like some clarification on precisely what advice he is trying to give here.我想澄清一下他在这里试图给出的确切建议。 Should I not make a singleton or static utility class at all (and use just a class) when I have some variables that affect that class?
当我有一些影响 Z2AB61A2DEB22ED4F8 的变量时,我是否应该根本不制作 singleton 或 static 实用程序 class(并且只使用一个类)? Or I can use it, but just need to use dependency injection?
或者我可以使用它,但只需要使用依赖注入? Which of these strategies would be most consistent with Bloch's advice?
这些策略中的哪一个最符合布洛赫的建议?
Joshua is talking about classes that are gateways to resources like databases, filesystems, or all kinds of network resources. Joshua 谈论的类是通往数据库、文件系统或各种网络资源等资源的网关。 They are hard to replace with alternative implementations.
它们很难用替代实现来代替。 If you just use regular classes, potentially implementing an abstract interface, you can inject them wherever they are needed and replace them by injecting something else instead.
如果您只使用常规类,可能实现一个抽象接口,您可以在任何需要它们的地方注入它们,并通过注入其他东西来替换它们。 The prime example of such alternative implementations are Mocks/Stubs/Fakes used in unit tests where you do not want to access the actual underlying resources.
这种替代实现的主要示例是在您不想访问实际底层资源的单元测试中使用的 Mocks/Stubs/Fakes。 Other examples:
其他示例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.