← Back to Home
Interpreter Pattern
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
What is it?
The Interpreter pattern provides a way to evaluate language grammar or expressions.
Example
interface Expression { interpret(context: string): boolean; } class TerminalExpression implements Expression { constructor(private data: string) {} interpret(context: string): boolean { return context.includes(this.data); } } class OrExpression implements Expression { constructor(private expr1: Expression, private expr2: Expression) {} interpret(context: string): boolean { return this.expr1.interpret(context) || this.expr2.interpret(context); } } class AndExpression implements Expression { constructor(private expr1: Expression, private expr2: Expression) {} interpret(context: string): boolean { return this.expr1.interpret(context) && this.expr2.interpret(context); } } // Usage example: const cat = new TerminalExpression('cat'); const dog = new TerminalExpression('dog'); const orExpression = new OrExpression(cat, dog); console.log(orExpression.interpret('dog is friendly')); // true const andExpression = new AndExpression(cat, dog); console.log(andExpression.interpret('cat and dog')); // true
Common Uses
- Parsing expressions
- SQL or regex interpreters
- Compilers and calculators
When to Use
- When you have a grammar to represent
- When you want to interpret sentences in a language
Caution
- Can become complex for large grammars
- Not efficient for complex parsing