簡體   English   中英

工廠設計模式通用返回類型

[英]Factory Design Pattern Generic return Type

我想用通用返回類型實現工廠設計模式。 我已經創建了這個示例,但無法使其正常工作。 我的工廠如何返回通用類型,以及如何在主類中使用它。 這是我的代碼:

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

您不必將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>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM