Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

java - Did Joshua Bloch say not to use singleton with underlying resources?

I have been reading Joshua Bloch's Effective Java book. 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? Or I can use it, but just need to use dependency injection? Which of these strategies would be most consistent with Bloch's advice?

question from:https://stackoverflow.com/questions/65642503/did-joshua-bloch-say-not-to-use-singleton-with-underlying-resources

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Joshua is talking about classes that are gateways to resources like databases, filesystems, or all kinds of network resources. 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. Other examples:

  • replace reading from JSON files by reading from YAML files
  • replace reading/writing from/to one database system with something that reads/writes from/to another database system
  • replace routing via google maps by reading from here.com
  • etc.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...