5

I have an application which has some classes that handle some specific functions, have a lifetime equal to the application itself, and are meant to be used in many parts of the program. For this last reason i call them Services. For example, the Audio Service plays audio files and does many other things related to audio.

Theese classes are instantiated only once at applications startup and it does not make any sense to have more than one per type.

Since i've read many answers about singletons here on SO where their usage is discouraged, i went on by passing a reference to thoose services when needed. As the project is growing i find myself with many classes which need a service reference on their constructor and in some cases even a facade to those services to avoid adding all the services references.

I think i'm doing it wrong. I think this should be a good use for static/singleton classes.

Is this a correct approach?

Zmaster
  • 1,095
  • 9
  • 23

4 Answers4

2

It seems like you need a dependency injection container with some autowiring capabilities. In case you are using Java, consider Spring for example.

Infeligo
  • 11,715
  • 8
  • 38
  • 50
1

I see one answer suggests introducing Spring. Under the covers, Spring is still passing that reference around where it is needed.

Rather than introducing a new framework into the app, why not just use a Singleton? If it does the job and is easier to maintain than passing a service reference around, I say use it.

If your concern about Singletons is because of their impact on testability, use Dependency Injection (the pattern, not a framework) to decrease coupling to an implementation.

Mike G
  • 4,713
  • 2
  • 28
  • 31
0

Singleton actually stands for objects that should be created just only one time only during the application life cycle. These objects actually contain some of the fixed settings. Let's say you got a parser class that is for parsing just only html. The root of HTML should be "" tag. In addition, you don't want to create loads of instances from this parser class because every instance of class will do the same thing. Instance will get a string of html and will give you back X. If you think that your classes will do just only one thing at a time, you can go for singleton. However, if you say that, for instance, your Audio Service should play different audios at a time, I THINK creating instance of a class is better than making it singleton.

kkocabiyik
  • 4,246
  • 7
  • 30
  • 40
0

I agree with MikeG. Use a singleton. Since you say these classes are mostly service oriented I wouldn't expect it to cause any problems.

King
  • 339
  • 1
  • 5