类型约束http://docs.manew.com/csharp/117.html
    image.png

    1. using System;
    2. using System.Collections.Generic;
    3. namespace FactoryModern
    4. {
    5. class Program
    6. {
    7. static void Main(string[] args)
    8. {
    9. //声明加人类工厂
    10. AbstractHumanFactory factory = new HumanFactory();
    11. //第一次造白种人
    12. IHuman human = factory.CreateHuman<WhiteHuman>();
    13. human.GetColor();
    14. human.Talk();
    15. //第二次造黑人
    16. human = factory.CreateHuman<BlackHuman>();
    17. human.GetColor();
    18. human.Talk();
    19. }
    20. }
    21. public interface IHuman
    22. {
    23. void GetColor();
    24. void Talk();
    25. }
    26. class BlackHuman : IHuman
    27. {
    28. public void GetColor()
    29. {
    30. Console.WriteLine("My Color is black.");
    31. }
    32. public void Talk()
    33. {
    34. Console.WriteLine("My language is xxxx");
    35. }
    36. }
    37. class WhiteHuman : IHuman
    38. {
    39. public void GetColor()
    40. {
    41. Console.WriteLine("My Color is white.");
    42. }
    43. public void Talk()
    44. {
    45. Console.WriteLine("My language is english");
    46. }
    47. }
    48. class YellowHuman : IHuman
    49. {
    50. public void GetColor()
    51. {
    52. Console.WriteLine("My Color is yellow.");
    53. }
    54. public void Talk()
    55. {
    56. Console.WriteLine("My language is chinese");
    57. }
    58. }
    59. public abstract class AbstractHumanFactory
    60. {
    61. //where约束T为class类型,必须是来自IHuman或者是实现IHuman接口,可创建实例
    62. public abstract T CreateHuman<T>() where T : class,IHuman,new();
    63. }
    64. public class HumanFactory : AbstractHumanFactory
    65. {
    66. public override T CreateHuman<T>()
    67. {
    68. IHuman human = null;
    69. try
    70. {
    71. human = new T();
    72. }
    73. catch
    74. {
    75. Console.WriteLine("人种生成错误");
    76. }
    77. return (T)human;
    78. }
    79. }
    80. }