Dominik
Dominik

Reputation: 599

Passing objects vs. Singleton

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

Upvotes: 1

Views: 1143

Answers (3)

Cerad
Cerad

Reputation: 48865

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

Upvotes: 1

Kamil
Kamil

Reputation: 13931

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.

Upvotes: 0

AbstractProblemFactory
AbstractProblemFactory

Reputation: 9811

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

Upvotes: 2

Related Questions