Flex & Actionscript Singleton Model Class

In many of the projects and applications I build with Flex I use a singleton for the Model – we’ve talked about Singletons in the past here. Whether this is the preferred method of handling a model is a matter of opinion so I won’t be discussing it. However, I do want to share the model class that I typically use. Actionscript lacks a real static constructor, used for creating a single instance of a class, which means creating a nice singleton takes a bit more work.

To create the singleton I take advantage of using a local class definition inside of my model Actionscript file. From my understanding the local class, it is only visible and valid inside of the file. Also I owe props to some blog for pointing this trick out but I can’t remember the blog – sorry. This means we can ensure that the only instance of the model is created inside of the class. Let’s take a look of the entire code below and we can make a little more sense of it.

package
{
  [Bindable]
  public class MainModel
  {
    private static var _instance:MainModel = new MainModel(ModelEnforcer);
   
    public static function getInstance():MainModel
    {
      return _instance;
    }
   
    public function MainModel(enforcer:Class)
    {
      if(enforcer != ModelEnforcer) {
        throw new Error("Use MainModel.getInstance to access model");
      }
    }
 
  }
}

class ModelEnforcer {}

Ok so above we have the ever so popular GetInstance method which is what all external files will use to get an instance of the model. This will check if the local static variable for the single instance is populated and if not calls the constructor which takes the aforementioned local class. Inside the constructor you can initialize whatever you need to and basically everything else in the class is going to a public variable or a convenience method.

To summarize, we have a local class that makes sure that the only instance is created inside the MainModel class. And, of course, use GetInstance to grab the instance. That is pretty much it. If you have any questions or want to simply comment on using this method feel free to leave a comment.

Leave a Reply

Your email address will not be published.