主要用到了[单例,抽象工厂,缓存,N层,反射]等知识。架构图如下:
解决方案用到的项目列表如下:
- 在接口项目中,定义一个IUER接口。
namespace IDAL { public interface IUser { int Delete(string userId); int Delete(Entity.User user); } }
2.在DALSQLProvider项目中,进行对IUSER接口的实现,针对SQL SERVER数据库。[Oracle同]
namespace DALSQLProvider { public class User : IDAL.IUser { #region IUser 成员 public int Delete(string id) { throw new NotImplementedException();//ADO.NET } public int Delete(Entity.User user) { throw new NotImplementedException();//ADO.NET } #endregion } }
3.DALFactory类库项目实现抽象出对所有接口(相当于一个系列),以后进行产品族选择配置(4)。
namespace DALFactory { public abstract class DalFactory { //一个系列,里面接口数量对应于IDAL中的接口 public abstract IDAL.IUser UserDALProvider { get; } } }
4.DALSQLProvider项目对DALFactory类库项目进行实现,返回DALSQLProvider项目User类的实例[Orcale同]
namespace DALSQLProvider { public class UserDALSQLFactory : DALFactory.DalFactory { public override IDAL.IUser UserDALProvider { get { // return new User(); //添加缓存,避免每次都NEW对象。 DALSQLProvider.User obj = System.Web.HttpContext.Current.Cache.Get("IDAL.IUser") as DALSQLProvider.User; if (obj == null) { var instance = new User(); System.Web.HttpContext.Current.Cache.Add("IDAL.IUser", instance, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); return instance; } return obj; } } } }
5.业务逻辑层实现数据访问层定义的接口。在这个地方用反射根据加载的程序集(DALSQLProvider.dll/DALOracleProvider.dll)进行实例化类。用单例保证不出现多个对象。
namespace BLL { public class DALProvider { private static DalFactory instance; private DALProvider() { } static DALProvider() { //根据WebConfig获取具体的provider string dllFileName = System.Web.Configuration.WebConfigurationManager.AppSettings["DataProviderDllFile"]; string dalFactoryClassName = System.Web.Configuration.WebConfigurationManager.AppSettings["DataProviderFactoryName"]; System.Reflection.Assembly dll = System.Reflection.Assembly.LoadFile(System.Web.HttpContext.Current.Server.MapPath("~/DataProvider/" + dllFileName));//把要加载的程序集放在项目的DataProvider目录下, instance = dll.CreateInstance(dalFactoryClassName) as DalFactory; } public static DalFactory DefaulProvider { get { return instance; } } } }
namespace BLL { public class User { DalFactory provider = DALProvider.DefaulProvider; public int deleteUser(string id) { return provider.UserDALProvider.Delete(id); } } }
6.业务逻辑在页面进行展现。
protected void Button1_Click(object sender, EventArgs e)
{
BLL.User u = new BLL.User();
this.Button1.Text = u.deleteUser("1").ToString();
}