Interpreter Design Pattern

COMP 310  Java Resources  Eclipse Resources

(Back to Design Patterns)

Summary: The Intepreter Design Pettern is the basis for recursive algorithms on composite structures

The Interpreter design pattern is usually described in terms of interpreting grammars. In this discussion, we will focus on a more general usage with regards to operations on Composite design pattern structures.

The Interpreter pattern is very useful for adding functionality to Composite pattern structures. Composites represent multi-part systems that are being accessed as single abstract entities (e.g. as AComponent below). The Intepreter pattern requires an abstract method at the top level of the composite structure that is used by the component's client to process the entire structure. Concrete methods are thus implemented in the terminal and non-terminal components to do the actual processing.

Figure 1: UML diagram of interpreter pattern.
Interpreter Design Pattern UML Diagram
Interpreter Design Pattern UML Diagram

 

The abstract AComponent defines an abstract operation() to process the entire composite structure. The concrete components define concrete operation()'s to process themselves. The Composite class defines a concrete operation() as well, which in addition to any particular processing that it needs, must also recursively call operation() on all of its composees.

EXAMPLE 1

Suppose we have the following binary tree structure that holds int values. AIntTree represents the abstract tree. Leaf is a leaf node and holds a single int, data. InternalNode is an internal node with two branches, left and right, which are AIntTrees.

Figure 2: UML diagram of intepreter pattern demo.
Interpreter Pattern Example
erpreter Pattern Example

 

To add the ability to sum the contents of the entire tree, an abstract sum() method is added to the AIntTree superclass. A client that holds a reference to an AIntTree object will call sum() on that object. Concrete sum() methods are added to both the Leaf and InternalNode sub-classes. Leaf.sum() simply needs to return the value of data. InternalNode.sum() simply returns the sum of the left and rightsums.

 

 


Originally published in Connexions (CNX): https://web.archive.org/web/20101208035935/http://cnx.org/content/m16877/latest/

© 2023 by Stephen Wong