package {
public class Multiton {
public var test:String = "";
private static var _okToCreate:Boolean;
private static var _instances:Object = new Object();
private static var _instanceNum:int = 0;
public function Multiton() {
if (_okToCreate) {
_instanceNum++;
trace("created instance: " +_instanceNum);
} else {
throw new Error(this + " is a Multiton... you must use the getInstance() method to instantiate it.");
}
}
public static function getInstance(key:String="default"):Multiton {
if (!_instances[key]) {
_okToCreate = true;
_instances[key] = new Multiton();
_okToCreate = false;
}
return _instances[key];
}
}
}
Holding off on the follow up to yesterdays post because I haven’t finished it…. instead, here’s a Multiton – Just like a Singleton but with multiple instances. You use it like this:
var m0:Multiton = Multiton.getInstance("one");
m0.test = "i am instance one";
var m1:Multiton = Multiton.getInstance("two");
m1.test = "i am instance two";
// elsewhere in the app
var multiton:Multiton = Multiton.getInstance("one");
trace(multiton.test);
trace(Multiton.getInstance("two").test);
I’ve used this a few times and I seem to recall the Pure MVC makes use of this pattern (could be wrong about that though).