I have this abstract factory pattern that I use in as3 that I am pretty used to and I am trying to implement it in C# but lack some knowledge, here how it goes.
public class Factory{
static public ID_LOGIC_CLASS:int = AddClassLink(MyLogicClass);
static private classLib:Array;
public Factory(){
classLib = new Array();
}
static public AddClassLink(logicClass:Class):int {
classLib.push(logicClass);
return classLib.length-1;
}
static public CreateClassFromId(int id,
constructorData:DataObject):FactoryObject{
var c:Class = classLib[id];
var obj:FactoryObject = new c();
obj.Init(constructorData);
return obj;
}
}
This is the implementation I use and it is very good. It allows you to instantiate objects with a simple int and a data object that holds all of your constructor values.
Only thing that I am missing really is how to make a list of classes object in C# and how to create a new object of that class with a reference to the class type.
I think it could be done by using delegate’s constructors.
Tell me what you think.
Here’s a verbatim port:
In this example I’ve used a
Dictionary<TKey, TValueinstead of Array so that removals from the type dictionary don’t mess up the ID you are returning. In the above example, so long as AddClassLink is not called on multiple threads, you will get a unique ID every time, even if classes are deregistered.Regarding instantiation of a type, use the System.Type overload of
Activator.CreateInstance. This can construct an object given its runtime type only.Regarding usage of this class, if you have a class you want to register with it you would use this notation
The above should work (Disclaimer: Untested!) and should be an accurate port of your actionscript code. *That is not to say it is a good idea or best practices! *
I recommend taking a look into Dependency Injection containers and looking at the Factory Pattern in .NET as the power of reflection, runtime typing etc allow this pattern to be implemented elegantly and robustly in C#. In particular, DI Containers will allow you to register and resolve a class as follows
The main use of the container is to wire up dependencies and allow constructor injection as interfaces, leading to well decoupled, easily testable code, however it is essentially a typed object factory.