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(){}}
Roar
2 months ago
5 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)
Post a Comment