繁体   English   中英

必须在业务层注入规范吗?

[英]Must Inject the Specifications on Business Layer?

我正在尝试学习有关依赖注入和规范模式的一些事情。

如果我有这种情况:我有三种方法,它们有不同的验证规则。 此规则由规范验证。 所以...我的班级必须在构造函数上收到这样的规格吗?

public PostService(IRepositorio rep, ISpecificationSave ss, SpecificationGet g, ISpecificationDelete sd) { 
  // do things...
}

但如果这是正确的,当我添加一个新方法时,我需要更改de构造函数以接收更多的规范?

或者,即使使用Dependency Inject,更好的是,在这种情况下,在方法上创建一个规范实例,如何使用规范:

public void DoSomeThing(MyObject object) {
     Specification<MyObject> specification = new Specification<MyObject>();
     // do things...
}

我知道这个问题对你们中的一些人来说很简单,但我正在努力学习这些模式。

您可以在每个验证器中使用这些规范,通​​过它们在您的班级中逐个添加,使用Specitication Pattern,如下所示:

public Class Class1 : IClass1 {
    private List<ISpecification> contents;
    private List<ISpecification> specializations;

    public List GetContents() {
        return contents;
    }

    public Set GetFeatures() {
         return specifications;      
    }

    public Class1() {
        features = new List<ISpecification>(){//put specializations who belongs this class here};
        specialications = new List<ISpecification>();
    }   

    public boolean Validator1() {
        foreach(ISpecification as spec in this.specializations) {
            if (!spec.GetSpecification().IsSatisfiedBy(this))
                return false;
        }
        return true;
    }
}

public class Specification1 : ISpecification {
  private object requiredFeature;

  public Specification1(object feature) {
     requiredFeature = feature;
  }

  public boolean IsSatisfiedBy(IClass class) {
     return class.GetFeatures().contains(requiredFeature);  
  }
}

然后,您可以通过以下方式在应用中添加规范:

IClass1 class = new Class1();
class.GetFeatures().add(new Specialization1(// some feature));
class.GetFeatures().add(new Specialization2(// some feature));
class.GetFeatures().add(new Specialization3(// some feature));

暂无
暂无

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

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