Wednesday, February 6, 2008

Implementing Singleton in Flex

Your singleton class should look somewhat like this

package managers {
  /*A singleton class which enforces only a single object is created for each key. To access the specific instance, use getInstance(key:String) */

  public class MySingleton{
    private static var instanceMap:Object = new Object();

    public function MySingleton(pri:PrivateClass){}

    public static function getInstance(key:String):MySingleton{
      if(MySingleton.instanceMap[key] == null){
        MySingleton.instanceMap[key] = new MySingleton(new PrivateClass());
      }
      return MySingleton.instanceMap[key];
    }
  }
}

/* PrivateClass is used to make constructor private (to implement Singleton)*/
class PrivateClass{ public function PrivateClass(){}}

7 comments:

Anonymous said...

Why is there and indexer if it is a singleton? Surely that makes it a not a singleton but something else?

Saveen said...

The class allows you to have a singleton for one given key. For a true singleton you can do away with the key and have only one instance of the MySingleton class that you return using getInstance method.

Stanislav Zayarsky said...

What if I send null in the constructor?

Chris said...

Great point. You could still do "new Singleton(null)". I still like this approach because it makes the constructor "harder" to call accidentally letting the compiler help with accidents.

Anonymous said...

Hey.
Curious to know if i could create a copy by using ObjectUtil.copy(obj:Object)

Anonymous said...

@ Anonymous Question of using copy() from ObjectUtil class.

It returns null object if you typecast to the Singleton class like.

_instance4ID = (ObjectUtil.clone(_instance3ID)) as MySingleton;

If you don't typecast it( i.e, leave as Object class instance) then it returns you new Object of Object class :)

Anonymous said...

@ Anonymous Question of using copy() from ObjectUtil class.

It returns null object if you typecast to the Singleton class like.

_instance4ID = (ObjectUtil.clone(_instance3ID)) as MySingleton;

If you don't typecast it( i.e, leave as Object class instance) then it returns you new Object of Object class :)