1. 程式人生 > 其它 >結構型設計模式之-工廠方法(這個應該不算設計模式的一種)

結構型設計模式之-工廠方法(這個應該不算設計模式的一種)

先看程式碼:

 1     //工程方法
 2     public class Create
 3     {
 4         static void Main()
 5         {
 6             IBuySome buySome = new FactoryBuy().GetBuy(ClassType.ByFruits);
 7         }
 8     }
 9     public interface IBuySome
10     {
11         void Buy();
12     }
13 
14     public class ByPen : IBuySome
15 { 16 public void Buy() 17 { 18 Console.WriteLine("買筆"); 19 } 20 } 21 public class ByFruits : IBuySome 22 { 23 public void Buy() 24 { 25 Console.WriteLine("水果"); 26 } 27 } 28 public class BySugar : IBuySome
29 { 30 public void Buy() 31 { 32 Console.WriteLine("買糖果"); 33 } 34 } 35 36 public class FactoryBuy 37 { 38 public IBuySome GetBuy(ClassType classType) 39 { 40 switch (classType) 41 { 42 case ClassType.ByFruits:
43 return new ByFruits(); 44 case ClassType.ByPen: 45 return new ByPen(); 46 case ClassType.BySugar: 47 return new BySugar(); 48 default: 49 throw new Exception("沒有這個列舉!"); 50 } 51 } 52 } 53 public enum ClassType 54 { 55 ByFruits, 56 BySugar, 57 ByPen 58 }
View Code

這個模式依賴抽象!也就是一個共同的介面。為什麼在寫一個工廠來去例項化呢,那不是違反了低耦合原則了嗎?是違反了低耦合的原則,但是滿足了擴充套件需求。每個設計模式都不是完美的,都是解決一類問題,但是解決一類問題也會引發其他問題。為了解決這個耦合問題。就可以(反射+配置檔案)

 1 //工廠模式
 2     public class Create
 3     {
 4         static void Main()
 5         {
 6             IBuySome buySome= new FactoryBuy().GetBuy();
 7             //這樣擴充套件就很方便。有新功能新增,直接實現原有介面,然後該下配置檔案。就不需要修改原始碼。
 8             //就很好的解決了上面工廠方法的問題
 9         }
10     }
11     public interface IBuySome
12     {
13         void Buy();
14     }
15 
16     public class ByPen : IBuySome
17     {
18         public void Buy()
19         {
20             Console.WriteLine("買筆");
21         }
22     }
23     public class ByFruits : IBuySome
24     {
25         public void Buy()
26         {
27             Console.WriteLine("水果");
28         }
29     }
30     public class BySugar : IBuySome
31     {
32         public void Buy()
33         {
34             Console.WriteLine("買糖果");
35         }
36     }
37 
38     public class FactoryBuy 
39     {
40         public IBuySome GetBuy()
41         {
42             ///獲取dll的地址 比如:"C:\Users\guoyz\source\repos\HYC_C_CeShi\HYC_C_CeShi_ExtendCore\bin\Debug\CeShi_ExtendCore.dll"
43             var StrDllPath = ConfigurationManager.AppSettings["path"];
44             //獲取型別  比如:ByPen 就是這個
45             var StrType = ConfigurationManager.AppSettings["Type"];
46             Assembly assembly = Assembly.Load(StrDllPath);
47             //獲取具體型別
48             Type type = assembly.GetType(StrType, false, true);
49             //獲取型別
50             return (IBuySome)Activator.CreateInstance(type);
51         }
52     }
View Code

本文來自部落格園,作者:小換哥,轉載請註明原文連結:https://www.cnblogs.com/haunge/p/15034915.html