问题
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):
- create the object and pass it through the object tree (e.g. in the constructor)
- 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