引言
昨天加了一天班,今天闲来无事,就在想如何将之前的三层和最近一直在学的设计模式给联系在一起,然后就动手弄了个下面的小demo。
项目结构
项目各个层实现
Wolfy.Model层中有一个抽象类BaseModel.cs,User.cs是用户实体类,继承与BaseModel类,是用于类型安全考虑的,让各实体类有个统一的父类,在其他层使用的时候,可以使用里氏替换原则的考虑。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Wolfy.Model 8 { 9 /// <summary> 10 /// 该抽象类为所有实体类的父类, 11 /// 所有实体类继承该抽象类, 为保持类型一致而设计的父类,也是出于安全性的考虑 12 /// </summary> 13 public abstract class BaseModel 14 { 15 } 16 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Wolfy.Model 8 { 9 /// <summary> 10 /// 实体类user继承自BaseModel 11 /// 调用时就可以通过BaseModel model=new UserModel(); 12 /// </summary> 13 public class UserModel : BaseModel 14 { 15 public int Id { get; set; } 16 public string UserName { set; get; } 17 public string Password { set; get; } 18 } 19 }
Wolfy.FactoryDAL层是用于反射获取实例,其中只有一个类。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Wolfy.FactoryDAL 8 { 9 public class DataAccess<T> where T : class 10 { 11 //获取配置路径 12 private static readonly string path = System.Configuration.ConfigurationManager.AppSettings["DAL"]; 13 private DataAccess() { } 14 /// <summary> 15 /// 创建实例 反射创建实例 16 /// </summary> 17 /// <param name="type"></param> 18 /// <returns></returns> 19 public static T CreateDAL(string type) 20 { 21 string className = string.Format(path + ".{0}", type); 22 try 23 { 24 return (T)System.Reflection.Assembly.Load(path).CreateInstance(className); 25 26 } 27 catch (Exception ex) 28 { 29 throw new Exception(ex.Message.ToString()); 30 } 31 } 32 } 33 }