I’m learning about Singleton pattern using GoF’s book. I have a problem when I read it’s consequence:
- More flexible than class operations: Another way to package a singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.
I really don’t understand this explanation. I think class operation (static method) can allow more than one instance of a class too, if I use static list of instances, but I know I’m wrong, of course.
So, anybody can give me some examples to help me understand this problem? Thanks so much!
The original idea is that you make a use only static members in the class, and static methods that operate only on these static members, and then use the class itself as a singleton. No runtime istantiation needed or allowed – and if you do istantiate anything, it is of another type (an instance, not a class. in smalltalk it is an instance of a class, and not an instance of a metaclass).
So, if you manage a list of such instances, you did not create multiple instances of this type; you have created a singleton (the class) that have in it list of a non-singleton-type instances.
In a sense, every class is a singleton. It’s just that it is not usually a good idea to use one as a singleton object in your program, for the reasons mentioned in the text.