Skip navigation

A Singleton class can save your rear. But, is a singleton good or evil? Is it just a way of defining global vars? You decide, while I ‘ll continue to use them and stay out of the debate, one that I don’t really understand anyway.

Putting aside one of the many debates on Singleton usage, there’s certainly a compelling reason to use one. Consider it a safe place to store your application variables, where you’ll only ever need one instance of those vars throughout the lifetime of your application. This can really save you from getting in a mess by instantiating more than one class in error. I don’t recall where I found this class, but they’re all very much the same.

package com.flexdesigner.model
{

    [Bindable]
    public class DataModel
    {
	    // Single instance of our DataModel
	    private static var instance : DataModel;

		public function DataModel(enforcer:SingletonEnforcer)
		{
			if (enforcer == null)
			{
				throw new Error( "Only one model allowed!" );
			}

		}

		// Returns the single instance
		public static function getInstance() : DataModel
		{
			if (instance == null)
			{
				instance = new DataModel( new SingletonEnforcer );
			}
			return instance;
		}

		// viewstack
	   	public var viewState : uint = LOGIN_VIEW;
	   	public static const LOGIN_VIEW : uint = 0;
		public static const MAIN_VIEW : uint = 1;

       }
}

// Utility Class to Deny Access to Constructor
class SingletonEnforcer {};

In order to use the DataModel class within your code, simply set a variable of type DataModel to be the returned instance:

private var _model : DataModel = DataModel.getInstance();

_model.someVar;
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: