设计模式~简单工厂模式(Factory)

时间:2024-04-05 09:37:52

简单工厂模式Simple Factory根据提供给它的数据,返回一个类的实例。通常它返回的类都有一个公共的父类(或者接口对象)。

简单工厂的作用是实例化对象,而不需要客户了解这个对象属于哪个具体的子类。简单工厂实例化的类具有相同的接口或者基类,在子类比较固定并不需要扩展时,可以使用简单工厂。如数据库生产工厂就是简单工厂的一个应用。
         采用简单工厂的优点是可以使用户根据参数获得对应的类实例,避免了直接实例化类,降低了耦合性;缺点是可实例化的类型在编译期间已经被确定,如果增加新类 型,则需要修改工厂,不符合OCP(开闭原则)的原则。简单工厂需要知道所有要生成的类型,当子类过多或者子类层次过多时不适合使用。

下面是我实例中的类结构图,它有一个ICreate的公共接口,有一个方法叫Create,返回值为Void

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPgAAABrCAIAAADVQdixAAAQs0lEQVR4nO2dy28bxxnA+QcEPRXoYdM/YA9BD00uVMFDi4q6NbdCSx3aBKQOSeqgaalnAieWjCCIY4gMYEmUDFkPsC4qUXUaUZFi6xGliSm3QPygKHlFiWL1AhQlcd3YSCG0h9l57uxyV5SzpPgBv8Nqdufbb3Z/OzsjcLC+RDK98a99ADjd+EB0oBYA0YGaAEQHagIQHagJfIlkeqO4L+Xbw1zhzz/89jBndQAAVAuWoiPL/1Po/rz3R+A6UO3IRUeWPyycf5h96Zvl5wXXjw6OPM8bAFwhEd3oyze7/519+cHy81/NP/vlhz9+84WnkOtHB0e3w3cq1PWleF1D/IbnaQCVhy+RTOeL+wQ8YjmPLP96/rkvP3waWZ7Hln83/h1yPV+81dkQUFSOuvO32IByluJ1DfHr0nI2jtVhZYRV1ICitgyWEw2oQkTR0bj84cpL3yw///X8s4e4L88zln/X+9/7r+rvPnOBVjwZIyebVK1zCW83T7puj43ox1AWRD9FSHr0y60/+Gb5V1/NP/vVjZ+8+cJTZ85eQuReXmUtPzo4ohUFJ2gPaoh7/bxm9KYN8evMe4Dv/iebhL4WhV2K1zW0NDUEFDXQ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+e7e6PHXRxvrA4oaaBwy6jYOob1GOVPSM2VOQGYJTYl9ulQSjU+SBoz24sRaw+jPm631gcYhEoFEM18Z3EDT9ZHFd9Y0rwWqFkTRs9h18uXorL595uylrL4tfDmaqyW9naypuKQ3TEWZMmXTayyOHs+K1bXWG9vZoahCNthyHe2K9hphpQmIQxd63qGoEh7Pcr4KjRpvVI1dU29pSngc2UYPNiIwG7IrM/WWpkjTk8d31jSvBaoWJKJnsevI8iwWPatvky9Hi1XYiy6xCvWUjF72N2koauhOe3TcmbEb4tOltQ5ZaC09HXuYGI1PUmydOaDhX2+Yf1TMZ5FenxLxbZvmtUDVglz0rL5NLM8yomf1bfLlaPF2srdKLjGje+neaLyR3O9jiG6lLFvCDhvKFR0pbhp6WZ3apqSk6NCLHwtL0VmI6MKXoy1uHn0Rk72Nxlj8Zms9HjSzr2Biv3nQ4lB0MpjhRwKy9MQSPKKQDV2MJGVDC8mTw0w52EaJaprSs49v3zTAGS5EN385mh5jORkN4FGpOPtEw3E8z0M+0fkfN4m0EV14iUtmbBbDEjIfQIuOTbWQTHySshNR8DNMr4D1u8tuPCPMVks1zWuBqgWnoku/HO1x9hX1Hi/nX4cV3rRTgSPREcKXoz1PvaJskExDT0vTTgcuRM/q2+TL0Z7nDQCucCd6Vt8Gy4FqxJdIpu/p2wBwuvElkul797cB4HTzfx5wC5exx5unAAAAAElFTkSuQmCC" alt="" />

其中公用的接口代码如下:(最后工厂的返回值类型)

1    /// <summary>
/// 简单工厂接口,返回值类型
/// </summary>
4 public interface ICreate
5 {
6 void Create();
7 }

而下面,分别用people和animal两个类去实现了ICreate接口,并实现了它的Create方法。

 1      /// <summary>
/// 人类实现工厂接口
/// </summary>
4 public class People : ICreate
5 {
6
7 #region ICreate 成员
8
9 public void Create()
10 {
11 Console.WriteLine("创建人类");
12 }
13
14 #endregion
15 }
16 /// <summary>
/// 动物实现工厂接口
/// </summary>
19 public class Animal : ICreate
20 {
21
22 #region ICreate 成员
23
24 public void Create()
25 {
26 Console.WriteLine("创建动物");
27 }
28
29 #endregion
30 }

而对于外界来说,会有另一个类去为外界提供服务,它们可以需要建立People或者Animal类型的实现,代码如下:

 1     public class CreateFactory
2 {
3 public static ICreate GeneratorCreate(string createName) {
4 switch (createName)
5 {
6 case "People":
7 return new People();
8 case "Animal":
9 return new Animal();
10 default:
11 throw new NotImplementedException();
12 }
13 }

最后,在使用它时,直接使用CreateFactory.GeneratorCreate("类型条件名")即可生成你的类对象了。

以上内容转自 张占岭