规约模式(Specifications)

规范模式 是一种特定的软件设计模式,通过使用布尔逻辑(Wikipedia)将业务规则链接在一起,可以将业务规则重新组合起来。

在实践中,它主要用于为实体或其他业务对象定义可重用的过滤器

示例

    public class KeyRoleSpecification : Specification<Role>
    {
        string _keyword = "";
        string _fieldName = "";
        public KeyRoleSpecification(string keyword, string fieldName)
        {
            _keyword = keyword;
            _fieldName = fieldName;
        }
        public override Expression<func<Role>, bool=bool>> GetExpression()
        {
            Expression<func<Role, bool=bool>> spec = null;
            switch (_fieldName)
            {
                case "Name":
                    spec = c => c.Name.IndexOf(_keyword) != -1;
                    break;
            }
            return spec;
        }
    }

提示:Linq模糊查询

n.Name.StartsWith(Name)--相当于A%
n.Name.EndsWith(Name) --相当于%A
n.Name.IndexOf(Name)!=-1 --相当于%A%
var listWhere = list.Where(n=>n.Name.StartsWith(Name)|| n.Name.EndsWith(Name)||
n.Name.IndexOf(Name)!=-1);

var listWhere = list.Where(n=>n.Name.Contains(Name));

 public partial class RoleService : IRoleService
    {
        private readonly IRepository<role> _roleRepository;
        private readonly ICacheManager _cacheManager;
        public RoleService(ICacheManager cacheManager, IRepository<Role> roleRepository)
        {
            this._cacheManager = cacheManager;
            this._roleRepository = roleRepository;
        }
        public int GetRoleCount(ISpecification<Role> spec)
        {
            var roles = _roleRepository.FindAll();
            var roleCount = 0;
            foreach (var role in roles)
            {
                if (spec.IsSatisfiedBy(role))
                {
                    roleCount++;
                }
            }
            return roleCount;
        }
    }

因此,我们可以将任何对象作为实现ISpecification<Role> 规约的接口的参数,该接口定义如下所示:

public interface ISpecification<T>
{
        bool IsSatisfiedBy(T obj);
}