Reputation: 425
i'm trying to do fancy stuff like this:
i have following code:
public interface IMyInterface
{
void Method1();
}
public interface IClassFactory
{
object GetObject();
}
public interface IGenericClassFactory<T> where T: IMyInterface
{
T GetObject();
}
public class MyClass : IMyInterface
{
public void Method1()
{
Console.WriteLine("Medota 1");
}
}
public class MyFactory : IClassFactory
{
public object GetObject()
{
return new MyClass();
}
}
public class MyGenericFactory<T> : IGenericClassFactory<T> where T : IMyInterface, new()
{
public T GetObject()
{
// T t = new T();
//return t;
//var ctor = typeof(T).GetConstructor(new Type[0]);//1] { typeof(int) });
//if (ctor != null)
//{
// return (T)ctor.Invoke(new object[0]); // new object[1] { 5});
// //return Activator.CreateInstance<T>(); //to samo co wyzej tylko nie jest bezpieczne
//}
//throw new InvalidOperationException("T nie posiada domyślnego konstruktora");
// return Activator.CreateInstance<T>(); //bez parametrów
// return (T)Activator.CreateInstance(typeof(T), 5, "EOG", new object()); // z parametrami
return new T();
}
}
static void Main(string[] args)
{
IClassFactory factory;
factory = new MyFactory();
IGenericClassFactory<IMyInterface> genFactory;
genFactory = new MyGenericFactory<MyClass>(); //Do not compile!
MyClass obj = genFactory.GetObject() as MyClass;
obj.Method1();
Console.ReadKey();
}
I can do this like:
IGenericClassFactory<IMyInterface> genFactory;
genFactory = new MyGenericFactory<MyClass>();
//so i can chose object to create
but i think it is pointless because i want to have Factory of more then one object. Can u help me?
Thx in advance
Upvotes: 1
Views: 144
Reputation: 6366
You should not make your factory class generic but the method GetObject
should be generic:
public T GetObject<T>() where T: IMyInterface, new()
Then:
static void Main(string[] args)
{
var factory = new MyFactory();
var obj = factory.GetObject<MyClass>();
obj.Method1();
Console.ReadKey();
}
So all in all you should get rid of your generic code and simply modify your MyFactory class
public class MyFactory : IClassFactory
{
public T GetObject<T>()
{
//TODO - get object of T type and return it
return new T();
}
}
By the way - I am not sure what is the purpose of having this generic implementation? Does it make any sense from the perspective of the usage of Factory pattern?
Upvotes: 2