added provider

This commit is contained in:
2013-11-13 16:12:53 +04:00
parent 7e7b974090
commit 971fce0904

31
haxework/provider/Provider.hx Executable file
View File

@@ -0,0 +1,31 @@
package haxework.provider;
import haxe.ds.ObjectMap;
import flash.errors.Error;
class Provider {
private static var factories:ObjectMap<Dynamic, Class<Dynamic>> = new ObjectMap<Dynamic, Class<Dynamic>>();
private static var instances:ObjectMap<Dynamic, Dynamic> = new ObjectMap<Dynamic, Dynamic>();
public static function setFactory<T>(i:Class<T>, clazz:Class<T>, ?type:Dynamic):Void {
factories.set(type == null ? i : type, clazz);
}
public static function set<T>(i:Class<T>, instance:T, ?type:Dynamic):Void {
instances.set(type == null ? i : type, instance);
}
public static function get<T>(i:Class<T>, ?type:Dynamic):T {
var key:Dynamic = (type == null) ? i : type;
if (instances.exists(key)) {
return instances.get(key);
} else if (factories.exists(key)) {
var instance:T = Type.createInstance(factories.get(key), []);
instances.set(key, instance);
return instance;
} else {
throw new Error("Factory for\"" + i + "\" not found");
}
}
}