Specification Pattern: TypeScript implementation
1 min readJun 16, 2018
The Specification pattern can be nicely applied to poker hand ranking.
These Specification
interface and AbstractSpecification
class can be used for specifications of all sorts. They include two logical operators “AND” and “NOT”:
interface Specification<T> {
isSatisfiedBy(candidate: T): boolean;
and(other: Specification<T>): Specification<T>;
not(): Specification<T>;
}abstract class AbstractSpecification<T> implements Specification<T> {
// See the implementation below
}
I’m going to use specifications to evaluate poker hands and determine if one does or does not satisfy some criteria. This is a dummy PokerHand
interface:
interface PokerHand {
// Details are omitted
}
If we implement basic poker hand specifications
class Straight extends AbstractSpecification<PokerHand> { ... }
class Flush extends AbstractSpecification<PokerHand> { ... }
class FourOfAKind extends AbstractSpecification<PokerHand> { ... }
class ThreeOfAKind extends AbstractSpecification<PokerHand> { ... }
class OnePair extends AbstractSpecification<PokerHand> { ... }
class TwoPair extends AbstractSpecification<PokerHand> { ... }
class HighCard extends AbstractSpecification<PokerHand> { ... }
we can combine them with logical operators. Straight flush can be expressed as Straight AND Flush:
const flush = new Flush();
const straight = new Straight();const straightFlush = straight.and(flush);
Full house is Three of a kind AND One pair:
const threeOfAKind = new ThreeOfAKind();
const onePair = new OnePair();const fullHouse = threeOfAKind.and(onePair);