Singletons is arguably the easiest to understand design pattern, and thus, one of the most frequently implemented design patterns, even- especially- when it isn't necessary. Its simplicity is its weakness.
Bartłomiej inherited some code which implemented this pattern many, many times. None of them worked quite correctly, and all of them tried to create a singleton a different way.
For example, this one:
public class SystemMemorySettings
{
private static SystemMemorySettings _instance;
public SystemMemorySettings()
{
if (_instance == null)
{
_instance = this;
}
}
public static SystemMemorySettings GetInstance()
{
return _instance;
}
public void DoSomething()
{
...
// (this must only be done for singleton instance - not for working copy)
if (this != _instance)
{
return;
}
...
}
}
The only thing they got correct was the static method which returns an instance, but everything else is wrong. They construct the instance in the constructor, meaning this isn't actually a singleton, since you can construct it multiple times. You just can't use it.
And you can't use it because of the real "magic" here: DoSomething
, which checks if the currently active instance is also the originally constructed instance. If it isn't, this function just fails silently and does nothing.
A common critique of singletons is that they're simply "global variables with extra steps," but this doesn't even succeed at that- it's just a failure, top to bottom.
