Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Created January 4, 2013 11:38
Show Gist options
  • Select an option

  • Save ChrisMcKee/4451971 to your computer and use it in GitHub Desktop.

Select an option

Save ChrisMcKee/4451971 to your computer and use it in GitHub Desktop.
Specification Pattern Template
namespace Specifications
{
public interface ISpecification<T>
{
bool IsSatisfiedBy(T candidate);
ISpecification<T> And(ISpecification<T> other);
ISpecification<T> Or(ISpecification<T> other);
ISpecification<T> Not();
}
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);
}
}
public class AndSpecification<T> : CompositeSpecification<T>
{
private readonly ISpecification<T> _left;
private readonly ISpecification<T> _right;
public AndSpecification(ISpecification<T> left, ISpecification<T> right)
{
_left = left;
_right = right;
}
public override bool IsSatisfiedBy(T candidate)
{
return _left.IsSatisfiedBy(candidate) && _right.IsSatisfiedBy(candidate);
}
}
public class OrSpecification<T> : CompositeSpecification<T>
{
private readonly ISpecification<T> _left;
private readonly ISpecification<T> _right;
public OrSpecification(ISpecification<T> left, ISpecification<T> right)
{
_left = left;
_right = right;
}
public override bool IsSatisfiedBy(T candidate)
{
return _left.IsSatisfiedBy(candidate) || _right.IsSatisfiedBy(candidate);
}
}
public class NotSpecification<T> : CompositeSpecification<T>
{
private readonly ISpecification<T> other;
public NotSpecification(ISpecification<T> other)
{
this.other = other;
}
public override bool IsSatisfiedBy(T candidate)
{
return !other.IsSatisfiedBy(candidate);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment