Interpreter Design Pattern (original) (raw)

Last Updated : 3 Jun, 2026

The Interpreter Design Pattern is a behavioral design pattern used to define and evaluate the grammar of a language. It represents language rules as classes and interprets expressions by combining smaller expressions into a tree-like structure.

**Example: A calculator application can use the Interpreter Pattern to evaluate expressions like 5 + 3 - 2 by representing numbers and operators as expression objects and interpreting the result.

Components

These components work together to parse, interpret, and evaluate expressions based on a defined grammar.

Real-Life Example

Consider yourself visiting a foreign nation where you are not fluent in the local tongue. To properly interact with the natives in such a situation, you might require the support of an interpreter.

Here's how the Interpreter pattern relates to this situation

Benefits of using the Interpreter Pattern

The Interpreter Pattern improves the organization, flexibility, and maintainability of language-processing applications.

InterpreterDesignPatternClassDiagram-(2)

Implementation Example

**Problem Statement:

Suppose we have a simple language that supports basic arithmetic operations, such as addition (+), subtraction (-), multiplication (*), and division (/). We want to create a calculator program that can interpret and evaluate arithmetic expressions written in this language.

Communication flow of the Interpreter Design pattern using expression " 2+3*4 ":

The interpreter processes the expression by building and evaluating an expression tree step by step.

Let's break down into the component wise code:

1. Client

The client provides input expressions and interacts with the interpreter.

C++ `

#include

class Expression { public: virtual int interpret() = 0; };

class NumberExpression : public Expression { private: int number; public: NumberExpression(int number) : number(number) {} int interpret() override { return number; } };

class AdditionExpression : public Expression { private: Expression* left; Expression* right; public: AdditionExpression(Expression* left, Expression* right) : left(left), right(right) {} int interpret() override { return left->interpret() + right->interpret(); } };

class MultiplicationExpression : public Expression { private: Expression* left; Expression* right; public: MultiplicationExpression(Expression* left, Expression* right) : left(left), right(right) {} int interpret() override { return left->interpret() * right->interpret(); } };

int main() { // Manually building AST for 2 + 3 * 4 Expression* expression = new AdditionExpression( new NumberExpression(2), new MultiplicationExpression( new NumberExpression(3), new NumberExpression(4) ) );

int result = expression->interpret();
std::cout << "Result: " << result << std::endl;
return 0;

}

Java

public class Client { public static void main(String[] args) {

    // Manually building AST for 2 + 3 * 4
    Expression expression = new AdditionExpression(
        new NumberExpression(2),
        new MultiplicationExpression(
            new NumberExpression(3),
            new NumberExpression(4)
        )
    );

    int result = expression.interpret();
    System.out.println("Result: " + result);
}

}

Python

class Expression: def interpret(self): pass

class NumberExpression(Expression): def init(self, number): self.number = number def interpret(self): return self.number

class AdditionExpression(Expression): def init(self, left, right): self.left = left self.right = right def interpret(self): return self.left.interpret() + self.right.interpret()

class MultiplicationExpression(Expression): def init(self, left, right): self.left = left self.right = right def interpret(self): return self.left.interpret() * self.right.interpret()

Manually building AST for 2 + 3 * 4

expression = AdditionExpression( NumberExpression(2), MultiplicationExpression( NumberExpression(3), NumberExpression(4) ) )

result = expression.interpret() print("Result:", result)

JavaScript

class Expression { interpret() {} }

class NumberExpression extends Expression { constructor(number) { super(); this.number = number; } interpret() { return this.number; } }

class AdditionExpression extends Expression { constructor(left, right) { super(); this.left = left; this.right = right; } interpret() { return this.left.interpret() + this.right.interpret(); } }

class MultiplicationExpression extends Expression { constructor(left, right) { super(); this.left = left; this.right = right; } interpret() { return this.left.interpret() * this.right.interpret(); } }

// Manually building AST for 2 + 3 * 4 const expression = new AdditionExpression( new NumberExpression(2), new MultiplicationExpression( new NumberExpression(3), new NumberExpression(4) ) );

const result = expression.interpret(); console.log('Result:', result);

`

2. Abstract Expression

Defines the common interface for interpreting expressions.

C++ `

#include

class Expression { public: virtual int interpret() = 0; };

Java

public interface Expression { int interpret(); }

Python

from abc import ABC, abstractmethod

class Expression(ABC): @abstractmethod def interpret(self): pass

JavaScript

class Expression { interpret() { throw new Error('Method interpret() must be implemented.'); } }

`

3. Terminal Expression

Represents basic language elements.

C++ `

#include class NumberExpression { private: int number; public: NumberExpression(int number) : number(number) {} int interpret() { return number; } };

Java

public class NumberExpression implements Expression { private int number;

public NumberExpression(int number) {
    this.number = number;
}

@Override
public int interpret() {
    return number;
}

}

Python

class NumberExpression: def init(self, number): self.number = number def interpret(self): return self.number

JavaScript

class NumberExpression { constructor(number) { this.number = number; } interpret() { return this.number; } }

`

4. Non-Terminal Expression

Represents composite language constructs.

C++ `

#include using namespace std;

class Expression { public: virtual int interpret() = 0; };

class AdditionExpression : public Expression { private: Expression* left; Expression* right;

public: AdditionExpression(Expression* left, Expression* right) : left(left), right(right) {} int interpret() override { return left->interpret() + right->interpret(); } };

class MultiplicationExpression : public Expression { private: Expression* left; Expression* right;

public: MultiplicationExpression(Expression* left, Expression* right) : left(left), right(right) {} int interpret() override { return left->interpret() * right->interpret(); } };

Java

public class AdditionExpression implements Expression { private Expression left; private Expression right;

public AdditionExpression(Expression left, Expression right) {
    this.left = left;
    this.right = right;
}

@Override
public int interpret() {
    return left.interpret() + right.interpret();
}

}

public class MultiplicationExpression implements Expression { private Expression left; private Expression right;

public MultiplicationExpression(Expression left, Expression right) {
    this.left = left;
    this.right = right;
}

@Override
public int interpret() {
    return left.interpret() * right.interpret();
}

}

Python

from abc import ABC, abstractmethod

class Expression(ABC): @abstractmethod def interpret(self): pass

class AdditionExpression(Expression): def init(self, left, right): self.left = left self.right = right

def interpret(self):
    return self.left.interpret() + self.right.interpret()

class MultiplicationExpression(Expression): def init(self, left, right): self.left = left self.right = right

def interpret(self):
    return self.left.interpret() * self.right.interpret()

JavaScript

class Expression { interpret() { throw new Error('Method interpret() must be implemented.'); } }

class AdditionExpression extends Expression { constructor(left, right) { super(); this.left = left; this.right = right; } interpret() { return this.left.interpret() + this.right.interpret(); } }

class MultiplicationExpression extends Expression { constructor(left, right) { super(); this.left = left; this.right = right; } interpret() { return this.left.interpret() * this.right.interpret(); } }

`

Complete code for the above example

Tomplete code for the above example is

C++ `

#include

class Expression { public: virtual int interpret() = 0; };

class NumberExpression : public Expression { private: int number; public: NumberExpression(int number) : number(number) {} int interpret() override { return number; } };

class AdditionExpression : public Expression { private: Expression* left; Expression* right; public: AdditionExpression(Expression* left, Expression* right) : left(left), right(right) {} int interpret() override { return left->interpret() + right->interpret(); } };

class MultiplicationExpression : public Expression { private: Expression* left; Expression* right; public: MultiplicationExpression(Expression* left, Expression* right) : left(left), right(right) {} int interpret() override { return left->interpret() * right->interpret(); } };

int main() { // Manually building AST for 2 + 3 * 4 Expression* expression = new AdditionExpression( new NumberExpression(2), new MultiplicationExpression( new NumberExpression(3), new NumberExpression(4) ) );

int result = expression->interpret();
std::cout << "Result: " << result << std::endl;
return 0;

}

Java

interface Expression { int interpret(); }

class NumberExpression implements Expression { private int number;

public NumberExpression(int number) {
    this.number = number;
}

@Override
public int interpret() {
    return number;
}

}

class AdditionExpression implements Expression { private Expression left; private Expression right;

public AdditionExpression(Expression left, Expression right) {
    this.left = left;
    this.right = right;
}

@Override
public int interpret() {
    return left.interpret() + right.interpret();
}

}

class MultiplicationExpression implements Expression { private Expression left; private Expression right;

public MultiplicationExpression(Expression left, Expression right) {
    this.left = left;
    this.right = right;
}

@Override
public int interpret() {
    return left.interpret() * right.interpret();
}

}

public class Client { public static void main(String[] args) {

    // Manually building AST for 2 + 3 * 4
    Expression expression = new AdditionExpression(
        new NumberExpression(2),
        new MultiplicationExpression(
            new NumberExpression(3),
            new NumberExpression(4)
        )
    );

    int result = expression.interpret();
    System.out.println("Result: " + result);
}

}

Python

from abc import ABC, abstractmethod

class Expression(ABC): @abstractmethod def interpret(self): pass

class NumberExpression(Expression): def init(self, number): self.number = number

def interpret(self):
    return self.number

class AdditionExpression(Expression): def init(self, left, right): self.left = left self.right = right

def interpret(self):
    return self.left.interpret() + self.right.interpret()

class MultiplicationExpression(Expression): def init(self, left, right): self.left = left self.right = right

def interpret(self):
    return self.left.interpret() * self.right.interpret()

if name == "main": # Manually building AST for 2 + 3 * 4 expression = AdditionExpression( NumberExpression(2), MultiplicationExpression( NumberExpression(3), NumberExpression(4) ) )

result = expression.interpret()
print(f"Result: {result}")

` JavaScript ``

class Expression { interpret() { throw new Error('Method not implemented.'); } }

class NumberExpression extends Expression { constructor(number) { super(); this.number = number; }

interpret() {
    return this.number;
}

}

class AdditionExpression extends Expression { constructor(left, right) { super(); this.left = left; this.right = right; }

interpret() {
    return this.left.interpret() + this.right.interpret();
}

}

class MultiplicationExpression extends Expression { constructor(left, right) { super(); this.left = left; this.right = right; }

interpret() {
    return this.left.interpret() * this.right.interpret();
}

}

// Manually building AST for 2 + 3 * 4 const expression = new AdditionExpression( new NumberExpression(2), new MultiplicationExpression( new NumberExpression(3), new NumberExpression(4) ) );

const result = expression.interpret(); console.log(Result: ${result});

``

When to use

Use this pattern when you need to define and evaluate structured language grammar in a flexible way.

When not to use

Avoid this pattern when it adds unnecessary complexity or performance overhead.