Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that’s a topic for another time.)
However, there are a few corner cases where even a stateless singleton can be useful:
- You expect to extend it with state in the foreseeable future.
- You need an object instance for some particular technical reason.
Example: Synchonization objects for the C#lock
or the Javasynchronized
statement. - You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.
Example: TheToolkit.getDefaultToolkit()
method in Java will return a singleton whose exact type is system dependent. - You want reference equality for a sentinel value.
Example:DBNull.Value
in C#.