首页 > 其他 > 详细

设计模式-抽象工厂模式

时间:2018-05-17 22:02:05      阅读:41      评论: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
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号