Page 1 of 1

Question on Singleton

Posted: Thu Mar 29, 2007 2:14 pm
by SwizzCodes
Hi all,

ok so this is all about the singleton pattern. I find it pretty usefull, but I often read, that singletons are anti-patterns and they are no good use for OOP because they sprinkle dependencies all over the place in my programm. Still, I find myself using this pattern quite often. I wrap it around database connections, sessions, user-objects, Error-message-collectors, Input-Controllers and so on. So what do you think, is this good practice? Or what should I use instead?

cya

Posted: Thu Mar 29, 2007 2:18 pm
by Benjamin
Instead of creating a bunch of singletons, you may want to look into creating a class which stores each instance of each class that you create. This way you can minimize memory usage while at the same time have access to a bunch of classes without having to code them all as singletons.

Posted: Thu Mar 29, 2007 2:36 pm
by SwizzCodes
oh, good idea. so that would be a singleton-registry which holds one instance per class that I use, right ? hmm why didn't I thought of this in the first place :)

Posted: Thu Mar 29, 2007 3:06 pm
by Jenk
not necessarily one instance per class.

Posted: Thu Mar 29, 2007 3:56 pm
by SwizzCodes
that's right, but I probably want to, since I use it to replace my singletons.

Posted: Thu Mar 29, 2007 4:44 pm
by Christopher
You also might want to look through the long list you provided to see if it is:

1. Actually possible for you code to create multiple instances improperly. Often programmers implement Singletons to protect against use cases that don't exist.

2. Possible to inject those objects into the objects that use them rather than accessing them as a global. The injection could be directly or via a Registry.