抽象工厂模式(Abstract Factory),提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
所有在用简单工厂的地方,都可以考虑用反射技术来去除switch或if,解除分支判断带来的耦合。
Demo:
interface IUser { void Insert(User user); User GetUser(int id); }
class User { private int _id; public int Id { get { return _id; } set { _id = value; } } private string _name; public string Name { get { return _name; } set { _name = value; } } }
class MySqlUser : IUser { public void Insert(User user) { Console.WriteLine("MySqlUser的Insert"); } public User GetUser(int id) { Console.WriteLine("MySqlUser的GetUser"); return null; } }
class SqlServerUser : IUser { public void Insert(User user) { Console.WriteLine("SqlserverUser的Insert"); } public User GetUser(int id) { Console.WriteLine("SqlserverUser的GetUser"); return null; } }
Abstract factory type and factory types:
interface IFactory { IUser CreateUser(); }
class MySqlFactory : IFactory { public IUser CreateUser() { return new MySqlUser(); } }
class SqlServerFactory : IFactory { public IUser CreateUser() { return new SqlServerUser(); } }
Test:
IFactory factory = new MySqlFactory(); IUser user = factory.CreateUser(); user.Insert(new User()); user.GetUser(1);
可以通过反射和配置文件改善抽象工厂模式:
<appSettings> <add key="DB" value="MySql"/> </appSettings>
class DataAccess { private static readonly string db = ConfigurationManager.AppSettings["DB"]; private static readonly string assemblyName = "ConsoleApplication1"; private static readonly string classPrefix = assemblyName + "." + db + "." + db; public static IUser CreateUser() { return (IUser)Assembly.Load(assemblyName).CreateInstance(classPrefix + "User"); //switch (db) //{ // case "SqlServer": // //return new SqlserverUser(); // case "MySql": // //return new MySqlUser(); // return (IUser)Assembly.Load(assemblyName).CreateInstance(classPrefix + "User"); // default: // throw new Exception("未实现"); //} } }
Test:
IUser user = DataAccess.CreateUser(); user.Insert(new User()); user.GetUser(1);
时间: 2024-11-05 19:03:58