类型约束:http://docs.manew.com/csharp/117.html
using System;
using System.Collections.Generic;
namespace FactoryModern
{
class Program
{
static void Main(string[] args)
{
//声明加人类工厂
AbstractHumanFactory factory = new HumanFactory();
//第一次造白种人
IHuman human = factory.CreateHuman<WhiteHuman>();
human.GetColor();
human.Talk();
//第二次造黑人
human = factory.CreateHuman<BlackHuman>();
human.GetColor();
human.Talk();
}
}
public interface IHuman
{
void GetColor();
void Talk();
}
class BlackHuman : IHuman
{
public void GetColor()
{
Console.WriteLine("My Color is black.");
}
public void Talk()
{
Console.WriteLine("My language is xxxx");
}
}
class WhiteHuman : IHuman
{
public void GetColor()
{
Console.WriteLine("My Color is white.");
}
public void Talk()
{
Console.WriteLine("My language is english");
}
}
class YellowHuman : IHuman
{
public void GetColor()
{
Console.WriteLine("My Color is yellow.");
}
public void Talk()
{
Console.WriteLine("My language is chinese");
}
}
public abstract class AbstractHumanFactory
{
//where约束T为class类型,必须是来自IHuman或者是实现IHuman接口,可创建实例
public abstract T CreateHuman<T>() where T : class,IHuman,new();
}
public class HumanFactory : AbstractHumanFactory
{
public override T CreateHuman<T>()
{
IHuman human = null;
try
{
human = new T();
}
catch
{
Console.WriteLine("人种生成错误");
}
return (T)human;
}
}
}