25.3. Singled Out — Bad Singleton, Bad

One of the most common criticisms (or at least one I keep hearing) is of Cairngorm's use of singletons. A search for "Flex Cairngorm criticisms" turns up an article at http://nwebb.co.uk/blog/?p=168, which states:

The main reason people tell me they dislike Cairngorm is due to its over-reliance on the Singleton design pattern, and I understand.

Singletons increase coupling between classes and make them difficult to unit test. Any class which retrieves a singleton instance becomes unnecessarily coupled to the fact that the class is a singleton — it treats it in a different manner from other classes (i.e., it uses an uncommon instantiation technique). Singletons can't be substituted without changing the source of the class which uses it, nor can they be swapped-out for an interface, because singleton instances are retrieved/instantiated with a call to a static method (getInstance() by convention) and you can't have a static method on an interface. This limits polymorphism, going against the OO maxim, "Program to an interface, not an implementation." Furthermore there is the issue of misplaced responsibility, as classes should not be responsible for limiting their own instantiation; that should be the responsibility of a factory or builder object.

The article goes on to suggest that a possible solution is passing references to the model around. So in other words, instead of this:

var model:SomeModel = SomeModel.getInstance();

You would do something ...

Get Professional Cairngorm™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.