码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-抽象工厂模式

时间:2018-05-17 22:04:03      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:抽象工厂模式   设计模式   

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,
其他不说了,其实就是工厂方法模式的扩展。
结合简单工厂+反射+配置文件才是王道。

设计模式-抽象工厂模式

标签:抽象工厂模式   设计模式   

原文地址:http://blog.51cto.com/5591787/2117704

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!