Computer Science Design Patterns/Interpreter

{{Computer Science Design Patterns/Page Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
 * mode={{{mode|reading}}}
 * page={{{page|{{SUBPAGENAME}}}}}
 * stage=25
 * stage date=29 Jan, 2014
 * stage comment=Add more illustrations.
 * previous=Flyweight
 * next=Iterator
 * content=

Examples
The following Reverse Polish notation example illustrates the interpreter pattern. The grammar: defines a language which contains reverse Polish expressions like: Following the interpreter pattern there is a class for each grammar rule.

Cost
This pattern is not expensive. It dramatically reduces the business code so there is only few code to handle.

Creation
If the code already exists, this pattern is a little expensive.

Maintenance
This pattern is very easy to maintain. There is no additional cost due to the pattern.

Removal
This pattern is easy to remove with refactoring operations from your IDE.

Advises

 * Use the  term to indicate the use of the pattern to the other developers.

Implementations
The following Backus–Naur form example illustrates the interpreter pattern. The grammar

defines a language that contains Reverse Polish Notation expressions like:

a b + a b c + - a b + c a - -

This structural code demonstrates the Interpreter patterns, which using a defined grammar, provides the interpreter that processes parsed statements.

Another example:

While the interpreter pattern does not address parsing, a parser is provided for completeness.

Finally evaluating the expression "w x z - +" with w = 5, x = 10, and z = 42.

Another example:

While the interpreter pattern does not address parsing a parser is provided for completeness. Finally evaluating the expression "w x z - +" with w = 5, x = 10, and z = 42.

As JavaScript is dynamically typed, we do not implement an interface.

Example 1:

Example 2: Based on the example above with another realization of the client.

Example 3: In a file we have the classes and the interface, defining the logic of the program (and applying the Interpreter pattern). Now the expr.php file: And the evaluate.php: And you can run on a terminal by typing php5 -f evaluator.php (or putting it on a web application).

}}