泛型+反射+三层实现工厂
2019-03-16 19:37 .net小跟班(杜) 阅读(414) 评论(0) 编辑 收藏 举报1、Web.config配置文件
<appSettings> <add key="webpages:Version" value="3.0.0.0"/> <add key="webpages:Enabled" value="false"/> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> <add key="DAL" value="DAL"/> </appSettings>
2、Model层创建BaseModel定义一个空的抽象类
//BaseModel 定义一个空的接口 public abstract class BaseModel { }
3、DAL层定义接口并实现方法; Factory代码如下:
//Factory public class Factory<T> where T:class { //获取配置文件 private static readonly string path = Path.Combine( ConfigurationManager.AppSettings["DAL"] ); private Factory() { } //创建实例 反射创建实例 public static T CreateDAL(string type) { string className= string.Format(path+".{0}",type); try { return (T)System.Reflection.Assembly.Load(path).CreateInstance(className); } catch (Exception) { throw; } } }
4、BLL层定义BaseBll类:
public class BaseBll<T> where T : Model.BaseModel, new() { protected IDataServer<T> Dal; public BaseBll(string type) { //通过工厂得到实例 Dal = Factory<IDataServer<T>>.CreateDAL(type); } public virtual int Add(T t) { return Dal.Add(t); } public virtual int Del(int id) { return Dal.Del(id); } public virtual int Upt(T t) { return Dal.Upt(t); } public virtual List<T> GetAll() { return Dal.GetAll(); } public virtual List<T> GetAllById(int id) { return Dal.GetAllById(id); } }
5、Bll层继承BaseBll,采用单例模式实现方法:
public class StudentBll:BaseBll<StudentInfo> { private const string _Type = "StudentDal"; private IDataServer<StudentInfo> _DAL; public StudentBll() : base(_Type) { _DAL = base.Dal as IDataServer<StudentInfo>; if (_DAL == null) { throw new NullReferenceException(_Type); } } public List<StudentInfo> GetList() { return _DAL.GetAll(); } }