i want implement factory design pattern generic return type. have created example can't work. how can factory return type of generic , how use in main class. here code:
namespace consoleapplication1 { using system; using system.collections.generic; class mainapp { static void main() { factory fac = new factory(); ipeople<t> pep = fac.getpeople(peopletype.rural); console.writeline(pep.getlist()); } } public interface ipeople<t> { list<t> getlist(); } public class villagers : ipeople<domainreturn1> { public list<domainreturn1> getlist() { return new list<domainreturn1>(); } } public class citypeople : ipeople<domainreturn2> { public list<domainreturn2> getlist() { return new list<domainreturn2>(); } } public enum peopletype { rural, urban } /// <summary> /// implementation of factory - used create objects /// </summary> public class factory { public ipeople<t> getpeople(peopletype type) { switch (type) { case peopletype.rural: return (ipeople<domainreturn1>)new villagers(); case peopletype.urban: return (ipeople<domainreturn2>)new citypeople(); default: throw new exception(); } } } public class domainreturn1 { public int prop1 { get; set; } } public class domainreturn2 { public int prop2 { get; set; } } }
you don't have pass enum
factory, t
type parameter can used select appropriate product this:
public class factory { public ipeople<t> getpeople<t>() { if(typeof(t) == typeof(domainreturn1)) return (ipeople<t>)new villagers(); if(typeof(t) == typeof(domainreturn2)) return (ipeople<t>)new citypeople(); throw new exception(); } }
and can use this:
factory factory = new factory(); var product1 = factory.getpeople<domainreturn1>(); var product2 = factory.getpeople<domainreturn2>();
Comments
Post a Comment