2. Factory 方法模式

來源:互聯網
上載者:User

定義一個使用者建立對象的介面,讓子類決定執行個體化哪一個類。使一個類的執行個體化延遲到其子類。 

工廠類與產品類往往具有平行的等級結構,它們之間一一對應。

 

相關類:

 1 namespace FactoryMethod
 2 {
 3 //日誌
 4     public abstract class Log
 5     {
 6         public abstract void WriteLog();
 7     }
 8 //資料庫日誌
 9 public class DBLog : Log
10     {
11         public override void WriteLog()
12         {
13             Console.WriteLine("DBLog Success!");
14         }
15     }
16 //文本日誌
17 public class TxtLog:Log
18     {
19         public override void WriteLog()
20         {
21             Console.WriteLine("TxtLog Success!");
22         }
23     }
24 //日誌工廠
25 public abstract class LogFactory
26     {
27         public abstract Log CreateLog();
28     }
29 //資料庫日誌工廠
30 public class DBLogFactory:LogFactory
31     {
32         public override Log CreateLog()
33         {
34             return new DBLog();
35         }
36     }
37 //文本日誌工廠
38 public class TxtLogFactory:LogFactory
39     {
40         public override Log CreateLog()
41         {
42             return new TxtLog();
43         }
44     }
45 //用戶端
46 class Program
47     {
48         static void Main(string[] args)
49         {
50             string assembly = ConfigurationManager.AppSettings["Assembly"];
51             string instance = ConfigurationManager.AppSettings["Instance"];
52             //應用反射來建立工廠,在更換工廠時,不需要修改代碼
53             LogFactory factory = (LogFactory)Assembly.Load(assembly).
54                 CreateInstance(instance);
55             Log log = factory.CreateLog();
56             log.WriteLog();
57             Console.ReadLine();
58         }
59     }
60 }

app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Assembly" value="FactoryMethod"/>
    <add key="Instance" value="FactoryMethod.DBLogFactory"/>
  </appSettings>
</configuration>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.