Saturday, October 17, 2009

Patterns - 039: Behavioral Patterns ( Interpreter )



In general, languages are made up of a set of grammar rules. Different sentences can be constructed by following these grammar rules.

Sometimes an application may need to process repeated occurrences of similar requests that are a combination of a set of grammar rules.These requests are distinct but are similar in the sense that they are all composed using the same set of rules.

In such cases, instead of treating every distinct combination of rules as a separate case, it may be beneficial for the application to have the ability to interpret a generic combination of rules.

The Interpreter pattern can be used to design this ability in an application so that other applications and users can specify operations using a simple language defined by a set of grammar rules.


Applying the Interpreter pattern:

  • A class hierarchy can be designed to represent the set of grammar rules with every class in the hierarchy representing a separate grammar rule.
  • An Interpreter module can be designed to interpret the sentences constructed using the class hierarchy designed above and carry out the necessary operations.

A language with extensive, complex grammar rules requires a large number of classes. The Interpreter pattern works best when the grammar is simple. Having a simple grammar avoids the need to have many classes corresponding to the complex set of rules involved, which are hard to manage and maintain.


Example

Let us build a calculator application that evaluates a given arithmetic expression. For simplicity, let us consider only add, multiply and subtract operations.

The Interpreter pattern can be applied in two stages:
  • Define a representation for the set of rules that make up the grammar for arithmetic expressions.
  • Design an interpreter that makes use of the classes that represent different arithmetic grammar rules to understand and evaluate a given arithmetic expression.
Arithmetic Expressions – Grammar


  • ArithmeticExpression::= ConstantExpression | AddExpression |MultiplyExpression | SubtractExpression
  • ConstantExpression::= Integer/Double Value
  • AddExpression::= ArithmeticExpression ‘+’ ArithmeticExpression
  • MultiplyExpression::= ArithmeticExpression ‘*’ ArithmeticExpression
  • SubtractExpression::= ArithmeticExpression ‘-’ ArithmeticExpression
Class Hierarchy Representing Grammar Rules for Arithmetic Expressions

( Figure 34.1 )

See the additional notes for Post order and algorithms


No comments:

Post a Comment