Applied Design Patterns with Java
Behavioral :: Interpreter (243) {C ch 18}
Collaborations
	- The client builds (or is given) the sentence as an abstract
	syntax tree of NonterminalExpression and TerminalExpression instances. Then the client initializes the context
	and invokes the Interpret operation.
	
 - Each NonterminalExpression node defines Interpret in terms
	of Interpret on each subexpression. The Interpret operation of each TerminalExpression defines the base case in
	the recursion.
	
 - The Interpret operations at each node use the context
	to store and access the state of the interpreter. 
 
Consequences
Interpreter
has the following benefits and liabilities:
	- It's easy to change and extend the grammar. Because the pattern uses classes to represent grammar rules, use inheritance to change
	or extend the grammar.
	Existing expressions can be modified incrementally, and new expressions can be defined as variations on old ones.
	
 - Implementing the grammar is easy. Classes defining nodes in the abstract syntax tree have similar implementations. These
	classes are easy to write, and often their generation can be automated with a compiler or parser generator.
	
 - Complex grammars are hard to maintain. The Interpreter pattern defines at least one class for every rule in the grammar (grammar rules defined
	using BNF
	may require multiple classes). Hence grammars containing many rules can be hard to manage and maintain. Other design
	patterns can be applied to mitigate the problem. But when the grammar is very complex, other techniques such as parser or compiler generators are more
	appropriate.
	
 - Adding new ways to interpret expressions. The Interpreter pattern makes it easier to evaluate an expression in a new way.
	It's easy to support pretty printing or type-checking an expression by defining a new operation on the expression
	classes. To keep creating new ways of interpreting an expression, consider using the Visitor (331) pattern to
	avoid changing the grammar classes. 
 
Catalog Behavioral Prev Next