1. 程式人生 > >設計模式-抽象工廠模式

設計模式-抽象工廠模式

抽象工廠模式 設計模式

public class UserEntity { public int ID { get; set; } public string Name { get; set; } } public interface IUser { void InsertUser(UserEntity user); UserEntity GetUser(int id); } class SqlUser: IUser { public void InsertUser(UserEntity user) { Console.WriteLine("在SQL中插入一個用戶"); } public UserEntity GetUser(int id) { Console.WriteLine("在SQL中獲取一個用戶"); return null; } } class AccessUser : IUser { public void InsertUser(UserEntity user) { Console.WriteLine("在Access中插入一個用戶"); } public UserEntity GetUser(int id) { Console.WriteLine("在Access中獲取一個用戶"); return null; } } //抽象工廠改簡單工廠->反射 public class SimpleFactory { private static string assemblyName = "抽象工廠"; private static string db = ConfigurationSettings.AppSettings["DB"]; public static IUser CreateUser() { //switch (db) //{ // case "sql":return new SqlUser(); // case "access": return new AccessUser(); //} //return null; string className = assemblyName + "." + db + "User"; IUser iuser = (IUser)Assembly.Load(assemblyName).CreateInstance(className); return iuser; } public static IDepartment CreateIDepartment() { string className = assemblyName + "." + db + "Department"; IDepartment department = (IDepartment)Assembly.Load(assemblyName).CreateInstance(className); return department; } } <appSettings> <add key="DB" value="Product.Sql"/> </appSettings> static void Main(string[] args) { //UserEntity user = new UserEntity(); //IFactory factory = new AccessFactory(); //IUser su = factory.CreateUser(); //su.InsertUser(user); //su.GetUser(1); //DepartmentEntity department = new DepartmentEntity(); //IDepartment de = factory.CreateDepartment(); //de.InsertDepartment(department); //de.GetDepartment(1); //Console.ReadLine(); UserEntity user = new UserEntity(); DepartmentEntity department = new DepartmentEntity(); IUser su = SimpleFactory.CreateUser(); su.InsertUser(user); su.GetUser(1); IDepartment dep = SimpleFactory.CreateIDepartment(); dep.InsertDepartment(department); dep.GetDepartment(1); Console.ReadLine(); }

總結:易於交換產品系列,例如把SQL換成MYSQL,
其他不說了,其實就是工廠方法模式的擴展。
結合簡單工廠+反射+配置文件才是王道。

設計模式-抽象工廠模式