So far, I’ve looked at two possible replacements for Cairngorm’s use of the Singleton pattern in its ModelLocator. I want to briefly introduce a third alternative before concluding this long string of posts.

The Singleton Factory

One complaint about the singleton pattern is that it forces the class to do two things – to implement the functionality of the class and to implement the factory for creating the singleton (the getInstance() static method and associated functionality).

The singleton factory is something I devised last year to remove the singleton implementation from the class and place it within an independent function. This also removes the singleton restriction, but that is often a desirable side effect – rather than restricting the class to have only one instance we create a factory for creating and accessing one instance globally while still allowing other instances to be created if desired.

The singleton factory looks like this…

package utils 
{
  public function SingletonFactory( c:Class ):*
  {
    return c in instances ? instances[c] : instances[c] = new c();
  }
}
import flash.utils.Dictionary;
var instances:Dictionary = new Dictionary( false );

The function receives a class as a parameter and returns an instance of that class. For any particular class, it will always return the same instance (the first time it is passed the class, it creates a new instance, any subsequent requests for that class return the same instance). You can read more about the singleton factory in this blog post.

So we could use this class with our Model to always use the same instance, as follows…

var model:UserModel = SingletonFactory( UserModel );

Where the UserModel class is implemented however we wish. The simplest would be…

package utils 
{
  public class UserModel
  {
    public var userName:String;
    public var firstName:String;
    public var lastName:String;
  }
}

The only restriction on the model is that the constructor shouldn’t require any parameters.

Next time I’ll wrap up this long stream of posts with some conclusions following my use of all three methods in a real project.