Pages

Sunday, July 23, 2017

Interpreter Pattern

Interpreter design pattern majorly used with languages and
notations. This pattern can be useful to convert from one language to another.
This pattern allows to write multiple rules or grammar for language to
interpret and extend easily. Interpreter Pattern falls under behavioral pattern
of GOF (Gang of Four) pattern.

When to use –

Interpreter Pattern is useful to interpret languages where
rules/grammar are complex part which you can easily extend using this pattern.
The pattern works on hierarchy of expression. The expression can be classified
as Terminal or Non-Terminal. The terminal expression is standalone and can be
Interpreted immediately. The non-terminal expression may contain one or more
terminal or non-terminal expressions.

Major components of Interpreter pattern –

Client – This client class responsible for build context,
terminal and non-terminal expression objects. It also responsible to make call
to interpret method of respective expression.

Context – This is context class used to store
input/output data and other information required by expression.

Expression – This is an interface which defines
Interpret method which will be implemented by sub classes.

NonTerminalExpression – This class will implement
Expression interface and implements Interpret method similar to TerminalExpression
class. This class may contain one or more terminal or non-terminal
expressions and invoke Interpret method respectively.

There are many examples available for Interpreter design
pattern. I would like to take simple example to understand the intent and
implementation for Interpreter design pattern. In my example I would like
interpret numbers to words. So I’ll provide number as input and that will be
interpreted by pattern to words. Similarly, you can add multiple rules to
interpret as per your requirement.

As you can see in this example, user set context value to
5642 and Interpret it to words via calling WordExpression which is terminal expression.
User also set value another context object ctx1 and set 397 value to Interpret
to word via calling SubExpression which is non-terminal expression and contains
reference of terminal expression. You can add multiple conversion rules and
interpret methods via adding multiple expressions as per your requirement.