Passing objects vs. Singleton

好久不见. 提交于 2019-12-11 05:27:28

问题


As far as I can see there are two main principles how to deal with application-wide role player objects like a root model object (in MVC context):

  1. create the object and pass it through the object tree (e.g. in the constructor)
  2. provide it as a singleton or other global variable technique

The first approach seems to be cleaner because the dependencies are better visible but there is a lot of additional work to do (parameters, class variables,...).

What do you prefer?

Edit: The first technique also uses only one instance but it is provided by passing the object and not by a static function


回答1:


I prefer run singletons' method getInstance() as constructor parameter - bake two birds with one stone ;)




回答2:


I think passing as parameter is a little more memory-efficient, easier to debug, but need a some additional work.

I prefer to use singletons only when i really need it (like database sessions, write to file etc.).

It really depends on project type, language, budget, size of project etc. There is no "universal" answer.




回答3:


This is where dependency injection can help out. Having to explicitly pass all the correct dependencies manually to an object whenever you create one can be a pain and perhaps somewhat error prone. A decent dependency injection container can help to automate this process and is actually easier to use than singletons.

The Symfony2 framework is a modern example:

http://symfony.com/doc/current/book/service_container.html



来源:https://stackoverflow.com/questions/9396664/passing-objects-vs-singleton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!