首先要建立部门类,假设只有两个字段部门ID,和部门名称。
public class Department
{
public int ID { get; set; }
public string DeptName { get; set; }
}
下面看一下添加了部门表的UML类图
IDAL
层的IDpartment
接口,用于客户端访问,解除与具体数据库访问的耦合。
interface IDepartment
{
void Insert(Department department);
Department GetDepartment(int id);
}
SqlServerDAL层DalSqlServerDepartment
类,用于访问Sql Server的Department
.
public class DalSqlServerDepartment: IDepartment
{
public void Insert(Department department)
{
Console.WriteLine("在Sql Server中给Department表增加一条记录");
}
public Department GetDepartment(int id)
{
Console.WriteLine("在Sql Server中根据ID得到Department表一条记录");
return null;
}
}
AccessDAL层的DalAccessDepartment
类,用于访问Access的Departmet
。
public class DalAccessDepartment : IDepartment
{
public void Insert(Department department)
{
Console.WriteLine("在Access中给Department表增加一条记录");
}
public Department GetDepartment(int id)
{
Console.WriteLine("在Access中根据ID得到Department表一条记录");
return null;
}
}
AbstractFactory层的IFactory
接口,定义一个创建访问Department
表对象的抽象的工厂接口。
interface IFactory
{
IDAL.IUser CreateUserDal();
IDAL.IDepartment CreateDepartmentDal();
}
在IFactory
接口中又新添加了CreateDepartment()
接口方法
SqlServerDAL层的SqlServerFactory
类,实现IFactory
接口,主要是实现Sql Server数据库添加了的部门接口方法。
public class SqlServerFactory : IFactory
{
public IUser CreateUserDal()
{
return new DalSqlServerUser();
}
public IDepartment CreateDepartmentDal()
{
return new DalSqlServerDepartment();
}
}
AccessDAL层的AccessFactory
类,实现IFactory
接口,主要是实现Access数据库添加了的部门接口方法。
public class AccessFavtory : IFactory
{
public IUser CreateUserDal()
{
return new DalAccessUser();
}
public IDepartment CreateDepartmentDal()
{
return new DalAccessDepartment();
}
}
客户端代码
class Program
{
static void Main(string[] args)
{
User user = new User();
Department dept = new Department();
IFactory factory = new AccessFactory();
IUser iu=factory.CreateUserDal();
iu.Insert(user);
iu.GetUser(1);
IDepartment id = factory.CreateDepartmentDal();
id.Insert(dept);
id.GetDepartment(1);
Console.ReadLine();
}
}
现在如果想切换数据库,只需要IFactory factory = new AccessFactory();
修改为IFactory factory=new SqlServerFactory();
只有一个Uer类和User操作类的时候,是只需要工厂方法模式的,但是现在显然你数据库中有很多的表,而Sql Server与Access又是两大不同的分类,所以解决这种涉及多个产品系列的问题,有一个专门的工厂模式叫抽象工厂模式。