三层架构之工厂模式(基于泛型)
1、目录
2、model层
2.1、BaseModel
namespace Study.Model { public abstract class BaseModel:IEquatable<BaseModel> { public bool Equals(BaseModel other) { throw new NotImplementedException(); } } }
2.2、User
namespace Study.Model { public class User:Model.BaseModel { private string userName; private int age; public string UserName { get { return userName; } set { userName = value; } } public int Age { get { return age; } set { age = value; } } } }
3、IDAL层
3.1、IBaseDAL
namespace Study.IDAL { public interface IBaseDAL<T> where T:Study.Model.BaseModel///T必须是BaseModel的派生类 { int add(T model); int delete(T model); int insert(T model); int update(T model); List<T> getList(T model); } }
3.2、IUserDAL
namespace Study.IDAL { public interface IUserDAL:IBaseDAL<User> { } }
4、BLL层
4.1、BaseBLL
namespace Study.BLL { public class BaseBLL<M> where M:Study.Model.BaseModel { private Study.IDAL.IBaseDAL<M> dal; private string DALClassName; public BaseBLL(string className) { DALClassName = className; dal = (Study.IDAL.IBaseDAL<M>)Study.FactoryDAL.DataAccess<M>.CreateDAL(DALClassName); } public int add(M model) { dal.add(model); return 0; } int delete(M model) { return 0; } int insert(M model) { return 0; } int update(M model) { return 0; } List<M> getList(M model) { List<M> a=new List<M>(); return a; } } }
4.2、UserBLL
namespace Study.BLL { public class UserBLL:Study.BLL.BaseBLL<Study.Model.User> { public UserBLL():base("UserDAL") { } } }
5、FactoryDAL
namespace Study.FactoryDAL { public class DataAccess<T> where T:Study.Model.BaseModel { public static readonly string path="Study.SQLServerDAL"; public static Study.IDAL.IBaseDAL<T> CreateDAL(string dalClassName) { string type = typeof(T).ToString(); System.Reflection.Assembly a= System.Reflection.Assembly.Load(path); return (Study.IDAL.IBaseDAL<T>)System.Reflection.Assembly.Load(path).CreateInstance(path+"."+dalClassName); } } }
6、Vie层
private void button1_Click(object sender, EventArgs e) { User user = new User(); Study.BLL.BaseBLL<User> baseUserBll = new Study.BLL.BaseBLL<User>("UserDAL"); Study.BLL.UserBLL userBLL = new BLL.UserBLL(); int a = baseUserBll.add(user); int b = userBLL.add(user); }
在veiw层里调用BLL层用反射机制动态反回DAL类时会出现程序集Study.SQLServerDAL找不到的错误,解决办法:在VIEW层里将Study.SQLServerDAL引用加上去。虽然view层不直接访问DAL层而是由BLL层来访问。