摘自《大话设计模式》一书。
程序入口:
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Reflection;
5 using System.Configuration;
6
7 namespace 抽象工厂模式
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 User user = new User();
14 Department dept = new Department();
15
16 IUser iu = DataAccess.CreateUser();
17
18 iu.Insert(user);
19 iu.GetUser(1);
20
21 IDepartment id = DataAccess.CreateDepartment();
22 id.Insert(dept);
23 id.GetDepartment(1);
24
25 Console.Read();
26 }
27 }
28 }
工厂方法:
1 class DataAccess
2 {
3 private static readonly string AssemblyName = "抽象工厂模式";
4 private static readonly string db = ConfigurationManager.AppSettings["DB"];
5
6 public static IUser CreateUser()
7 {
8 string className = AssemblyName + "." + db + "User";
9 return (IUser)Assembly.Load(AssemblyName).CreateInstance(className);
10 }
11
12 public static IDepartment CreateDepartment()
13 {
14 string className = AssemblyName + "." + db + "Department";
15 return (IDepartment)Assembly.Load(AssemblyName).CreateInstance(className);
16 }
17 }
数据实体类User和Department:
1 class User
2 {
3 private int _id;
4 public int ID
5 {
6 get { return _id; }
7 set { _id = value; }
8 }
9
10 private string _name;
11 public string Name
12 {
13 get { return _name; }
14 set { _name = value; }
15 }
16 }
1 class Department
2 {
3 private int _id;
4 public int ID
5 {
6 get { return _id; }
7 set { _id = value; }
8 }
9
10 private string _deptName;
11 public string DeptName
12 {
13 get { return _deptName; }
14 set { _deptName = value; }
15 }
16 }
数据操作:
1 interface IUser
2 {
3 void Insert(User user);
4
5 User GetUser(int id);
6 }
1 class SqlserverUser : IUser
2 {
3 public void Insert(User user)
4 {
5 Console.WriteLine("在Sqlserver中给User表增加一条记录");
6 }
7
8 public User GetUser(int id)
9 {
10 Console.WriteLine("在Sqlserver中根据ID得到User表一条记录");
11 return null;
12 }
13 }
1 class AccessUser : IUser
2 {
3 public void Insert(User user)
4 {
5 Console.WriteLine("在Access中给User表增加一条记录");
6 }
7
8 public User GetUser(int id)
9 {
10 Console.WriteLine("在Access中根据ID得到User表一条记录");
11 return null;
12 }
13 }
1 interface IDepartment
2 {
3 void Insert(Department department);
4
5 Department GetDepartment(int id);
6 }
1 class SqlserverDepartment : IDepartment
2 {
3 public void Insert(Department department)
4 {
5 Console.WriteLine("在Sqlserver中给Department表增加一条记录");
6 }
7
8 public Department GetDepartment(int id)
9 {
10 Console.WriteLine("在Sqlserver中根据ID得到Department表一条记录");
11 return null;
12 }
13 }
1 class AccessDepartment : IDepartment
2 {
3 public void Insert(Department department)
4 {
5 Console.WriteLine("在Access中给Department表增加一条记录");
6 }
7
8 public Department GetDepartment(int id)
9 {
10 Console.WriteLine("在Access中根据ID得到Department表一条记录");
11 return null;
12 }
13 }
以前总是把IUser接口这样的操作也写到数据库视图中,老是感觉不和谐。从抽象的角度看,数据库操作并不是实体User的必须方法,而且我也不是什么时候都需要调用数据的,如果把实体中增加了数据库操作方法,调用者恶意调用多麻烦!这里再分一个抽象的IUser专门管理数据库操作还是很好的。