简体   繁体   English

验证设计模式

[英]Validation Design Pattern

I am wrting a data validation utility for one of our department which has following requirement. 我正在为我们的一个部门提供数据验证实用程序,该实用程序具有以下要求。 - Dynamically adding new business entity - Dynamically adding new validations to an entity. - 动态添加新业务实体 - 动态地向实体添加新验证。 - An UI to display list of business entity and their validaiton - User will have option to start the validation on all or selcted business entity validaiton. - 用于显示业务实体及其有效性列表的UI - 用户可以选择在所有或选定的业务实体验证上启动验证。 - UI will display a validation error message if any validation fails. - 如果任何验证失败,UI将显示验证错误消息。 - System should proceed to the next validation even if any of the validation fails thus all configured validaiton are validated. - 即使任何验证失败,系统也应继续进行下一次验证,从而验证所有已配置的验证。

After searching internet I found following 2 promissing design pattern which satisfy my business requirement one id Decorator pattern and another is Chain of Command (aka Chain of Responsibilty). 在搜索互联网后,我发现以下2个承诺设计模式满足我的业务需求一个id装饰模式,另一个是命令链(又称责任链)。 Now my question is which is better? 现在我的问题是哪个更好? Anyone got any better idea? 有人有更好的主意吗?

Thanks 谢谢

I think what you want is the Specification Pattern . 我想你想要的是规格模式 So you would do something like this: 所以你会做这样的事情:

public void StartDateNotInPastSpecification : ISpecification<ISomeBusinessObject>
{
  public bool IsSatisfiedBy(ISomeBusinessObject myBusinessObject)
  {
    return myBusinessObject.StartDate >= DateTime.Now;
  }
}

The nice thing about this pattern is that each rule is easily testable in isolation and you get to choose when to apply the validation rules (as opposed to some frameworks which impose this decision on you). 关于这种模式的好处是每个规则都可以单独测试,你可以选择何时应用验证规则(而不是某些框架将这个决定强加给你)。

I'm using the Specification Pattern too. 我也在使用规范模式。 This is a basic implementation of it. 这是它的基本实现。

public class Specification<T, E> : ISpecification<T, E>
{
    private Predicate<T> predicate;

    public Specification(Predicate<T> predicate)
    {
        this.predicate = predicate;
    }

    public bool IsSatisfiedBy(T candidate)
    {
        return this.predicate.Invoke(candidate);
    }
}

With this implementation, I just pass a predicate in the constructor, like this: 通过这个实现,我只是在构造函数中传递一个谓词,如下所示:

var specification = new Specification<SomeDomainClass>(x => x.SomeDomainBoolMethod());

Instead of several classes (one per each condition in my domain), I have several bool methods in my business objects. 我的业务对象中有几个bool方法,而不是几个类(我的域中每个条件一个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM