I want to implement factory design pattern with a generic return type. I have created this example but I can't get it to work. How can my factory return a type of generic and how do I use it in main class. Here is my 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 to 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; }
}
}
Aucun commentaire:
Enregistrer un commentaire