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(){}}
Becoming a Freelancer as a Finance Professional
5 years ago
7 comments:
Why is there and indexer if it is a singleton? Surely that makes it a not a singleton but something else?
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.
What if I send null in the constructor?
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.
Hey.
Curious to know if i could create a copy by using ObjectUtil.copy(obj:Object)
@ 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 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 :)
Post a Comment