SOLID & Design Patterns Interview Question #48

What is the Specification Pattern?

Structural, Creational & Behavioral Patterns Mid-Level Intermediate

Quick Interview Answer

The Specification Pattern encapsulates a business rule or selection criterion in a reusable object. Specifications can sometimes be combined using AND, OR, or NOT operations to build more complex rules.

Detailed Explanation

The Specification Pattern encapsulates a business rule or selection criterion in a reusable object. Specifications can sometimes be combined using AND, OR, or NOT operations to build more complex rules.

It is useful when domain rules are reused across validation, querying, or decision logic. In data access, specifications should be designed so the persistence technology can translate the represented expressions efficiently.

Code Example

public interface ISpecification<T>
{
    bool IsSatisfiedBy(T item);
}

public class ActiveCustomerSpecification
    : ISpecification<Customer>
{
    public bool IsSatisfiedBy(Customer customer)
        => customer.IsActive;
}