一、定义:
抽象工厂模式:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
二、结构图:
三、代码实现:
IDepartment接口,用于客户端访问,接触与具体数据库访问的耦合:
interface IDepartment
{
void Insert(Department department);
Department GetDepartment(int id);
}
SqlserverDepartment类,用于访问SQL Server的Department。
class SqlserverDepartment:IDepartment
{
public void Insert(Department department)
{
Console.WriteLine("在 SQL Server 中给 Department 表增加一条记录");
}
public Department GetDepartment(int id)
{
Console.WriteLine("在 SQL Server 中给 Department 表增加一条记录");
return null;
}
}
AccessDepartment类,用于访问Access的Department。
class AccessDepartment:IDepartment
{
public void Insert(Department department)
{
Console.WriteLine("在Access中给Department表增加一条记录");
}
public Department GetDepartment(int id)
{
Console.WriteLine("在Access中根据ID得到Department表一条记录");
return null;
}
}
IFactory接口,定义一个创建访问Department表对象的抽象的工厂接口。
interface IFactory
{
IUser CreateUser();
IDepartment CreateDepartment();
}
SqlServerFactory类,实现IFactory接口,实例化SqlserverUser和SqlserverDepartment。
class SqlServerFactory:IFactory
{
public IUser CreateUser()
{
return new SqlserverUser();
}
public IDepartment CreateDepartment()
{
return new SqlserverDepartment();
}
}
AccessFactory类,实现IFactory接口,实例化AccessUser和AccessDepartment。
class AccessFactory:IFactory
{
public IUser CreateUser()
{
return new AccessUser();
}
public IDepartment CreateDepartment()
{
return new AccessDepartment();
}
}
客户端代码
static void Main(string[] args)
{
User user = new User();
Department dept = new Department();
//IFactory factory = new SqlServerFactory();
//IFactory factory = new AccessFactory();
IFactory factory = new AccessFactory();
IUser iu = factory.CreateUser();
iu.Insert(user);
iu.GetUser(1);
IDepartment id = factory.CreateDepartment();
id.Insert(dept);
id.GetDepartment(1);
Console.Read();
}
结果显示如下: