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