The Interpreter design pattern provides a solution:
(1)
Define a grammar for a simple language
by an Expression class
hierarchy.
(2)
Represent a sentence in the language
by an AST (abstract syntax tree).
(3)
Interpret a sentence
by calling interpret(context) on an AST.
Describing the Interpreter design in more detail is the
theme of the following sections.
See Applicability section for all problems Interpreter can solve.
Expression class hierarchy:
AbstractExpression | interpret(context)).
TerminalExpression)
that implement the interpretation.
NonTerminalExpression)
that forward interpretation to their child expressions.
TerminalExpression instances
(tExpr1,tExpr2,…)
and
NonTerminalExpression instances
(ntExpr1,ntExpr2,…).
interpret(context) on an AST.
Background Information