實現了ISpecification的對象則意味著是一個Specification,它可以通過與其他Specification對象的 And,Or或對自身的取反來生成新的邏輯。為了方便這些“組合邏輯”的開發,我們還會准備一個抽象的CompositeSpecification類:
public abstract class CompositeSpecification<T> : ISpecification<T>
{
public abstract bool IsSatisfIEdBy(T candidate);
public ISpecification<T> And(ISpecification<T> other)
{
return new AndSpecification<T>(this, other);
}
public ISpecification<T> Or(ISpecification<T> other)
{
return new OrSpecification<T>(this, other);
}
public ISpecification<T> Not()
{
return new NotSpecification<T>(this);
}
}
CompositeSpecification提供了構建復合Specification的基礎邏輯,它提供了And、Or和Not方法的實現,讓其他Specification類只需要專注於IsSatisfIEdBy方法的實現即可。例如,以下便是三種邏輯組合的具體實現:
public class AndSpecification<T> : CompositeSpecification<T>
{
private ISpecification<T> m_one;
private ISpecification<T> m_other;
public AndSpecification(ISpecification<T> x, ISpecification<T> y)
{
m_one = x;
m_other = y;
}
public override bool IsSatisfIEdBy(T candidate)
{
return m_one.IsSatisfiedBy(candidate) && m_other.IsSatisfIEdBy(candidate);
}
}
public class OrSpecification<T> : CompositeSpecification<T>
{
private ISpecification<T> m_one;
private ISpecification<T> m_other;
public OrSpecification(ISpecification<T> x, ISpecification<T> y)
{
m_one = x;
m_other = y;
}
public override bool IsSatisfIEdBy(T candidate)
{
return m_one.IsSatisfiedBy(candidate) || m_other.IsSatisfIEdBy(candidate);
}
}
public class NotSpecification<T> : CompositeSpecification<T>
{
private ISpecification<T> m_wrapped;
public NotSpecification(ISpecification<T> x)
{
m_wrapped = x;
}
public override bool IsSatisfIEdBy(T candidate)
{
return !m_wrapped.IsSatisfIEdBy(candidate);
}
}