最近一直在看DDD开发 规约似乎用得很普遍。 但是还是理解不了。所以记录下学习的进度。~
规约(Specification)模式
目的:查询语句和查询条件的分离
写了一个关于规约的模拟小程序
class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { OrderInfo o = new OrderInfo() { ID = i + 1, OrderTime = DateTime.Now, PorductID = new Random().Next(800, 810), Price = new Random().Next(123, 321), UserID = i + 1, UserName = "ZZQ" + i.ToString() }; SimulateDataBase.Add(o); } IRepository<OrderInfo> orderRespository = new OrderRepository(); OrderInfo orderInfo = orderRespository.GetEntity(new OrderInfoSpecification(2)); Console.WriteLine(orderInfo.UserName); Console.Read(); } } public class OrderInfo { public int ID { get; set; } public int UserID { get; set; } public string UserName { get; set; } public int PorductID { get; set; } public decimal Price { get; set; } public DateTime OrderTime { get; set; } } public interface IRepository<TEntity> where TEntity : class,new() { void Add(TEntity entity); IEnumerable<TEntity> GetEntitys(ISpecification<TEntity> specification); TEntity GetEntity(ISpecification<TEntity> specification); } public interface IOrderRepository : IRepository<OrderInfo> { } public class OrderRepository : IOrderRepository { public void Add(OrderInfo entity) { SimulateDataBase.Add(entity); } public IEnumerable<OrderInfo> GetEntitys(ISpecification<OrderInfo> specification) { return SimulateDataBase.OrderInfoList.Where(specification.IsSatisfiedBy); } public OrderInfo GetEntity(ISpecification<OrderInfo> specification) { return SimulateDataBase.OrderInfoList.Where(specification.IsSatisfiedBy).FirstOrDefault(); } } public interface ISpecification<TEntity> { bool IsSatisfiedBy(TEntity obj); //ISpecification<TEntity> And(ISpecification<TEntity> other); //ISpecification<TEntity> Or(ISpecification<TEntity> other); //ISpecification<TEntity> AndNot(ISpecification<TEntity> other); //ISpecification<TEntity> Not(); Expression<Func<TEntity, bool>> GetExpression(); } public abstract class Specification<TEntity> : ISpecification<TEntity> { public bool IsSatisfiedBy(TEntity obj) { return this.GetExpression().Compile()(obj); } public abstract Expression<Func<TEntity, bool>> GetExpression(); } public class OrderInfoSpecification : Specification<OrderInfo> { //private readonly OrderInfo order; //public OrderInfoSpecification(OrderInfo order) //{ // this.order = order; //} private readonly int userId; public OrderInfoSpecification(int userId) { this.userId = userId; } public override Expression<Func<OrderInfo, bool>> GetExpression() { return x => x.UserID == userId; } } public static class SimulateDataBase { private static List<OrderInfo> orderInfoList = new List<OrderInfo>(); public static IList<OrderInfo> OrderInfoList { get { return orderInfoList; } } public static void Add(OrderInfo order) { orderInfoList.Add(order); } }