Applied Design Patterns with Java
Behavioral :: Interpreter (243) {C ch 18}
Example - Java :: Patterns\Behavioral\Interpreter
Pattern Concept: to define a grammar for a language, and use that grammar to interpret statements in the
language. The Interpreter pattern drives three use cases:
- When a command Interpreter is needed to
parse user commands that allow a query facility that returns different results, based on the parsed input.
- When a program must parse an algebraic string, a common
occurrence in math and graphics packages.
- When a program must produce varied output different from
how the input is stored or represented, i.e.: like a Report Generator, or Traffic Analyzer, etc.
Interpreting a language takes three steps:
- parsing language symbols into tokens
- reducing the tokens into actions
- executing the actions
Examples - UML : SimpleParse and InterpDemo
Here is a sample parse output,
with a diagram showing the parse reduction, and the representive classes to accomplish this in UML:



Here is Cooper's Class Diagram for the application using this logic,
followed by the Rose equivalent:


The example Java program is called 'InterpDemo'.
The UML diagram is above, and the list of Java files is
below:

Issues and consequences of the Interpreter
pattern include:
- When an Interpreter
is used, an easy mechanism for the user to enter
commands in the language must be furnished;
- Generating a language and its grammar are non-trivial tasks,
requiring care and extensive testing, and the issue of what happens when a user enters a string that violates the
grammar
must be handled robustly and in a user-friendly manner;
- Even a GUI has an implied grammar behind it (proper values and sequencing of user actions in a given panel);
- The Interpreter
pattern has the advantage of being readily extensible, and a
grammar
can be revised, once the mechanism of parsing and reducing are fully understood and implemented;
- For grammars of any complexity (greater than six cases), use a class for each case. A large
grammar
may have many classes associated with it;
- Adding more complexity to a grammar is self-defeating; at some point, the grammar may become too complex to readily maintain.
Catalog Behavioral Prev Next