added provider
This commit is contained in:
31
haxework/provider/Provider.hx
Executable file
31
haxework/provider/Provider.hx
Executable 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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user