切换数据库类型示例:
1.User类:
public class User { public int Id { get; set; } public string Name { get; set; } }
2.AbstractProduct(以User为例):
public interface IUser { void Insert(User user); User GetUser(int id); }
3.Product(以User、SQL Server为例):
public class SqlserverUser:IUser { public void Insert(User user) { Console.WriteLine("在SQL Server中给User表增加一条记录"); } public User GetUser(int id) { Console.WriteLine("在SQL Server中根据Id得到User表中的一条记录"); return null; } }
4.AbstractFactory:
public interface IFactory { IUser CreateUser(); IDepartment CreateDepartment(); }
5.ConcreteFactory(以SQL Server为例):
public class SqlserverFactory:IFactory { public IUser CreateUser() { return new SqlserverUser(); } public IDepartment CreateDepartment() { return new SqlserverDepartment(); } }
6.客户端代码:
class Program { static void Main(string[] args) { IFactory factory = new SqlserverFactory(); IUser user = factory.CreateUser(); user.Insert(new User()); user.GetUser(1); } }
用简单工厂来改进抽象工厂:
1.DataAccess:
public class DataAccess { private static readonly string db = "Sqlserver"; //private static readonly string db = "Access"; public static IUser CreateUser() { IUser user; switch (db) { case "Sqlserver": user = new SqlserverUser(); break; case "Access": user = new AccessUser(); break; } return user; } public static IDepartment CreateDepartment() { IDepartment department; switch (db) { case "Sqlserver": department = new SqlserverDepartment(); break; case "Access": department = new AccessDepartment(); break; } return department; } }
2.客户端代码:
class Program { static void Main(string[] args) { IUser user = DataAccess.CreateUser(); user.Insert(new User()); user.GetUser(1); } }
反射+抽象工厂:
DataAccess:
using System.Reflection;
public class DataAccess { private static readonly string AssemblyName = "AbstractFactory";//程序集名称 private static readonly string db = "Sqlserver";//数据库类型 public static IUser CreateUser() { string className = AssemblyName + "." + db + "User"; return (IUser)Assembly.Load(AssemblyName).CreateInstance(className); } public static IDepartment CreateDepartment() { string className = AssemblyName + "." + db + "Department"; return (IDepartment)Assembly.Load(AssemblyName).CreateInstance(className); } }
反射+配置文件:
1.配置文件:
<configuration> <appSettings> <add key="DB" value="Sqlserver"/> </appSettings> </configuration>
2.DataAccess:
using System.Configuration;
public class DataAccess { private static readonly string AssemblyName = "AbstractFactory";//程序集名称 private static readonly string db = ConfigurationManager.AppSettings["DB"]; public static IUser CreateUser() { string className = AssemblyName + "." + db + "User"; return (IUser)Assembly.Load(AssemblyName).CreateInstance(className); } public static IDepartment CreateDepartment() { string className = AssemblyName + "." + db + "Department"; return (IDepartment)Assembly.Load(AssemblyName).CreateInstance(className); } }