vitek wrote:rogerborg wrote:
If you're trying to mimic a singleton, then using static members and methods might be a closer match...
That isn't a singleton either.
Point of order: nobody said that it was.
vitek wrote: It is a similar to a design pattern called the monostate. The method isn't usually static, but the data is static so that there is only ever one copy of the data (ignoring issues with static and shared libraries).
I prefer to make the methods static as well, since if there's no instance data, then there's no need to or benefit from creating an instance, and no need for any instance methods that might encourage doing so.
One of the things that I dislike about singletons is this:
Code: Select all
Singleton * foo = Singleton::getInstance();
Singleton * bar = Singleton::getInstance();
assert(foo == bar);
I can see very little point (pun ahoy!) in obtaining a pointer that will always have the same value and then calling an instance method on it, if the data can be static, and accessed through static members.
There's only an advantage if you want to delay instantiation of (singleton) instance data, which leads us to...
vitek wrote:The advantage of a true singleton over the monostate is that the singleton will be lazy initialized.
Indeed, but it's a dubious advantage, since...
vitek wrote:use of a singleton type pattern often leads to use of many of them, and interdependencies between them can cause problems at program startup or shutdown.
...which in practice can and in my experience does lead to ad hoc rules about when you can, can't and must instantiate singletons. In fact if you end up instantiating them in a fixed order early in startup in order to avoid problems, that seems to me to be a too-clever-by-half way of doing it all with statics, i.e. calling a explicit static instantiation method that initialises static members.
And the reason that I prefer doing
that is that it's clearer. If you have to force initialisation, a method called
initialise() is much more intellectually honest - and kind to maintainers - than hiding it behind an early call to a generic getInstance() method.
You may guess from this that I'm not exactly a raging fan of singletons. I think they're a very clever solution that can lead developers away from a dumb but simpler one. I
like dumb and simple, because it's easier to pick up two years down the line.
However, I wouldn't want to get too...
zealous about it.