需要帮助理解规范模式 - 继承

时间:2011-08-23 20:55:53

标签: c# inheritance specification-pattern

我认为这更像是一个继承问题,但由于我试图通过实施一个使用它的模式来更好地掌握它,我想我会问我的问题是为了更好地掌握。

如果你使用Specification Pattern,有许多规范都来自规范,你用一个包装器规范类包装它们:

示例:

public class CustomerCreditCheck : Specification<Customer> {
    private readonly UnlimitedCreditLimitSpecification unlimitedCreditLimitSpec = new UnlimitedCreditLimitSpecification();
    private readonly SufficientCustomerCreditAmountSpec sufficientCustCreditAmtSpec = new SufficientCustomerCreditAmountSpec();
    private readonly AcceptableCustomerCreditStatusSpecification acceptCustCreditStatusSpec = new AcceptableCustomerCreditStatusSpecification();

    public override bool IsSatisfiedBy(Customer customer) {

        return acceptCustCreditStatusSpec
               .And(unlimitedCreditLimitSpec.Or(sufficientCustCreditAmtSpec))
               .IsSatisfiedBy(customer);
    }
}

我的问题是:由于您将客户实体传递给acceptCustCreditStatusSpec的IsSatisfiedBy方法(第一个假设),客户实体如何传递给unlimitedCreditLimitSpec和SufficientCustCreditAmtSpec规范的IsSatisifedBy方法?

谢谢,

1 个答案:

答案 0 :(得分:1)

Specification<T>.AndSpecification<T>.Or方法构建一个Specification<T>,它接受​​T的实例,并根据逻辑定义的规范对其进行测试。

所以Specification<T>.And看起来像是:

public Specification<T> And(Specification<T> left, Specification<T> right) {
    return new SpecificationFromPredicate(
        t => left.IsSatisfiedBy(t) && right.IsSatisfiedBy(t)
    );
}

public class SpecificationFromPredicate<T> : Specification<T> {
    private readonly Func<T, bool> predicate;

    public SpecificationFromPredicate(Func<T, bool> predicate) {
        this.predicate = predicate;
    }

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

同样适用于Specification<T>.Or

所以重点是

acceptCustCreditStatusSpec
           .And(unlimitedCreditLimitSpec.Or(sufficientCustCreditAmtSpec))

是一个规范,给定t它返回

acceptCustCreditStatusSpec.IsSatisfiedBy(t) &&
    (unlimitedCreditLimitSpec.IsSatisfiedBy(t) ||
         sufficientCustCreditAmtSpec.IsSatisifedBy(t)
    );