简单的工厂
简单工厂模式就是把当有多个类对象,要被创建的时候,而在一个类里统一一个函数来管理创建这些实体类。这样做的好处是方便后期维护,接下来上代码,先来看看简单工厂的实现
首先,先建一个接口来规范一个方法
1 using System;
2 using System.Collections.Generic;
3
4 namespace NetFramework
5 {
6 public interface IRace
7 {
8 void ShowKing();
9 }
10 }
然后开始写一些要被创建的实体类,这些类都要继承于IRace这个接口(继承抽象),跟着是工厂类(这里写在一个脚本里,方便测试)
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace NetFramework
8 {
9 public class Human : IRace
10 {
11 public void ShowKing()
12 {
13 Console.WriteLine("King of the Human is sky");
14 }
15 }
16
17 public class NE : IRace
18 {
19 public void ShowKing()
20 {
21 Console.WriteLine("King of the NE is moon");
22 }
23 }
24
25 public class ORC : IRace
26 {
27 public void ShowKing()
28 {
29 Console.WriteLine("King of the ORC is TT");
30 }
31 }
32
33 public class Undead : IRace
34 {
35 public void ShowKing()
36 {
37 Console.WriteLine("King of the Undead is uu");
38 }
39 }
40
41 public class ObjectFactory
42 {
43 public static IRace CreateInstance(RaceType raceType)
44 {
45 IRace race = null;
46 switch (raceType)
47 {
48 case RaceType.Human:
49 race = new Human();
50 break;
51 case RaceType.NE:
52 race = new NE();
53 break;
54 case RaceType.ORC:
55 race = new ORC();
56 break;
57 case RaceType.Undead:
58 race = new Undead();
59 break;
60 default:
61 throw new Exception("wrong raceType");
62
63 }
64 return race;
65 }
66 }
67
68 /// <summary>
69 /// 对象判断使用枚举比较好
70 /// </summary>
71 public enum RaceType
72 {
73 Human=1,
74 NE=2,
75 ORC=3,
76 Undead=4
77 }
78 }
然后在Program类里来调用这个工厂
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace NetFramework
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 IRace Human = ObjectFactory.CreateInstance(RaceType.Human);
14 IRace NE = ObjectFactory.CreateInstance(RaceType.NE);
15 IRace ORC = ObjectFactory.CreateInstance(RaceType.ORC);
16 IRace Undead = ObjectFactory.CreateInstance(RaceType.Undead);
17
18 PlayWar3(Human);
19 PlayWar3(NE);
20 PlayWar3(ORC);
21 PlayWar3(Undead);
22
23 Console.ReadKey();
24 }
25
26 public static void PlayWar3(IRace iRace)
27 {
28 iRace.ShowKing();
29 }
30 }
31 }
看看输出结果也是正确输出了