第一次看到这个词 Specification 是在ABP框架中,起先没怎么太关注这个。
随着接触DDD领域驱动越来越来多,关于如何集中业务逻辑的问题,再次浮现在我脑中。
好吧,我不知道。
我知道如何使用很挫的方式集中业务逻辑,问题是业务越来越大时,“这种很挫的方式集中业务逻辑” 的这一种方法将会使业务逻辑代码变得乱七八糟。
而这种乱七八糟的代码的终点是 “屎山” 。没错,“屎山” 就是巨难整,看着就让人生厌的东西,如果有位后来者看见这玩意,我相信他会骂上一句,然后......
但愿这次学习和以后的使用 Specification 可以帮助我更上一层楼吧。
ISpecification<T> 规约定义
public interface ISpecification<T> { bool IsSatisfiedBy(T entity); Expression<Func<T, bool>> ToExpression(); }
Specification<T>抽象类
/// <summary> /// This base specification implements the IsSatisfiedBy method by compiling the expression from ToExpression. /// /// This is useful for general specifications to prevent duplicated logic. /// Beware that it is not very performant in situations where many specifications are dynamically constructed and combined. /// </summary> /// <remarks> /// see this project https://github.com/elsa-workflows/elsa-core . /// </remarks> public abstract class Specification<T> : ISpecification<T> {private Func<T, bool>? _predicate; public virtual bool IsSatisfiedBy(T entity) { _predicate ??= ToExpression().Compile(); return _predicate(entity); } public abstract Expression<Func<T, bool>> ToExpression(); public static implicit operator Expression<Func<T, bool>>(Specification<T> specification) { return specification.ToExpression(); } }
具体例子
例如,创建一Project类
public class Project { public string Id { get; set; } public string Name { get; set; } public int Size { get; set; } public ProjectType ProjectType { get; set; } } public enum ProjectType { A, B, C, }
创建一个用于判断Project id的规约类
public class ProjectIdSpecification : Specification<Project> { public string ProjectId { get; } public ProjectIdSpecification(string projectId) { ProjectId = projectId; } public override Expression<Func<Project, bool>> ToExpression() { return project => project.Id == ProjectId; } }
标签:set,string,get,规约,ToExpression,Specification,public From: https://www.cnblogs.com/youlicc/p/16878934.html