Wednesday, March 29, 2006

Singleton as anti-pattern

In 99% of the cases the singleton pattern is used as a global variable.

But as I said before, the singleton 's main problem is that it violates the Single Responsability Principle: we have a factory + an object.

But in some object-oriented languages (ruby, Smalltalk), classes are object-factories.
In these each object has it's own responsability. Clean: the class is a factory, the object is "... its responsability".

In a way, "singleton" is an antipattern, because of the language limitations.
In C++/java/C# you need to hide the constructor, and offer a static "getInstance()",
in ruby/smalltalk you need to overwrite the new message/method.

In c++/java/c# you wonder: "why can I instantiate objects from other classes, but not from this one", in ruby/smalltalk the API usage is uniform and clean.

No comments: