我们做项目的时候通常用以下几种架构
一.依赖三层进行开发
项目中有SqlServerDAL,BLL这俩个类库,SqlServerDAL有这样一个类CustomerDAL.cs类,在BLL层调用DAL层如下
SqlServerDAL.CustomerDAL dal = new SqlServerDAL.CustomerDAL();
public List<Model.Customer> GetList()
{
return dal.GetList();
}
这种做法会使模块间的耦合度特别大,我们的每个项目都要尽量达到模块内高内聚,模块间低耦合的要求
二.依赖接口进行开发
我们在项目中新加上一个类库IDAL,从名字我们就可以看出,这个项目里面全是SqlServerDAL里面的类实现的接口
public interface ICustomerDAL
{
List<Model.Customer> GetList();
}
我们再让 SqlServerDAL中的 CustomerDAL.cs类去实现这个接口, 在BLL层调用DAL层如下
IDAL.ICustomerDAL dal =new CustomerDAL();
public List<Model.Customer> GetList()
{
return dal.GetList();
}
这样做的好处是如果DAL层换了一个,例如把 SqlServerDAL换成AccessDAL,这时我们就不需要改动BLL里面的代码,但是这种情况,我们的
模块间的耦合还是存在的,因为当我们需要切换数据访问驱动层时(Ado.net,EF,Nh)时,还是需要改动BLL层,这种情况下,我们的简单工厂模式出现了
三.简单工厂模式
我们在解决方案中再次添加一个类库DALFactory,里面的SimpleFactory.cs类这样实现
public class SimpleFactory
{
public static IDAL.ICustomerDAL CreateCustomerDAL()
{
return new SqlServerDAL.CustomerDAL();
}
}
在BLL中这样调用
IDAL.ICustomerDAL dal = DALFactory.SimpleFactory.CreateCustomerDAL();
public List<Model.Customer> GetList()
{
return dal.GetList();
}
这时,我们发现无论是依赖的数据库改变,还是 切换数据访问驱动层(Ado.net,EF,Nh)时,我们都不需要改动BLL层
四.抽象工厂模式
/// 抽象工厂类,完成数据层中对象的创建(反射创建对象)
/// 程序集,命名空间
public class AbstractFactroy
{
private static string DalAssemblyPath = ConfigurationManager.AppSettings["DalAssemblyPath"]; //程序集所在位置
private static string NameSpace = ConfigurationManager.AppSettings["NameSpace"]; //命名空间
public static IDAL.ICustomerDAL CreateCustomerDAL()
{
string fullClassName = NameSpace + ".CustomerDAL";
return CreateInstance(DalAssemblyPath, fullClassName) as IDAL.ICustomerDAL;
//也可以return Assembly.Load(DalAssemblyPath).CreateInstance(DalAssemblyPath + ".CustomerDAL") as IDAL.ICustomerDAL;
//这时就不需要下面的CreateInstance方法
}
/// <summary>
/// 通过反射创建出类实例
/// </summary>
/// <param name="assemblyPath"></param>
/// <param name="fullClassName"></param>
/// <returns></returns>
public static object CreateInstance(string assemblyPath,string fullClassName)
{
object instance=Common.CacheHelper.Get(fullClassName);
if (instance == null)
{
var assembly = Assembly.Load(assemblyPath);//加载程序集
instance = assembly.CreateInstance(fullClassName);//创建出指定程序集下类的实例.
Common.CacheHelper.Insert(fullClassName, instance);
}
return instance;
}
}
//缓存函数定义
public class CacheHelper
{
/// <summary>
/// 根据键从缓存中取出数据
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static object Get(string key)
{
System.Web.Caching.Cache cache = HttpRuntime.Cache;
return cache[key];
}
public static void Insert(string key, object value)
{
System.Web.Caching.Cache cache = HttpRuntime.Cache;
cache.Insert(key, value);
}
}
在配置文件中添加这样的内容
<appSettings>
<add key="DalAssemblyPath" value="CZBK.Shop.SqlServerDAL"/>
<add key="NameSpace" value="CZBK.Shop.SqlServerDAL"/>
</appSettings>
在BLL层中进行如下调用
IDAL.ICustomerDAL dal = DALFactory.AbstractFactroy.CreateCustomerDAL();
public List<Model.Customer> GetList()
{
return dal.GetList();
}
及以后大多数情况下使用抽象工厂模式,更完美