工厂设计模式通用返回类型

时间:2016-01-24 19:32:37

标签: c# generics design-patterns factory

我想用通用返回类型实现工厂设计模式。我创建了这个例子,但是我无法让它工作。我的工厂如何返回一种通用类型,如何在主类中使用它。这是我的代码:

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; }
    }
}

1 个答案:

答案 0 :(得分:2)

您不必将Enum传递给工厂,T类型参数可用于选择相应的产品:

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();
    }
}

你可以像这样使用它:

Factory factory = new Factory();

var product1 = factory.GetPeople<DomainReturn1>();

var product2 = factory.GetPeople<DomainReturn2>();