2. 工厂方法模式
定义一个用户创建对象的接口,让子类决定实例化哪一个类。使一个类的实例化延迟到其子类。
工厂类与产品类往往具有平行的等级结构,它们之间一一对应。
相关类:
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 }
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>
<configuration>
<appSettings>
<add key="Assembly" value="FactoryMethod"/>
<add key="Instance" value="FactoryMethod.DBLogFactory"/>
</appSettings>
</configuration>