Design Patterns Java™ Workbook

(Michael S) #1

Chapter 25. Interpreter................................................................................................................................


Chapter 25. Interpreter


The interpreter pattern, like the STATE and STRATEGY patterns, distributes an operation
across a collection of classes. In such patterns, the effect of calling the operation depends on
the class of the object that receives the call. In both STATE and STRATEGY, the receiver of
an operation call is a single object. INTERPRETER takes the same idea and applies it to
a composition—in particular, a rich composite, or one with various ways of forming groups.


The INTERPRETER pattern is similar to the COMPOSITE pattern, which defines a common
interface for individual items and groups of items. COMPOSITE does not require various,
interesting ways of forming groups, although it allows this. For example,
the ProcessComponent hierarchy in Chapter 5, Composite, allows sequences and
alternations of process flows. In Interpreter, the idea that there are various types of
composition is essential.


The way a class composes other components defines how an INTERPRETER class will
implement, or interpret, a distributed operation. Each composite class in an instance of
INTERPRETER models a rule for how composition may occur. The intent of the INTERPRETER
pattern is to let you compose executable objects according to a set of composition rules that
you define. An interpreter object conducts the execution, or evaluation of a collection of
rules, letting you build expression evaluators and command languages.


An Interpreter Example.............................................................................................................................


The robots that Oozinoz uses to move material along a processing line come with an
interpreter that controls the robot and that has limited control of machines on the line. The
interpreter comes as a hierarchy of classes that encapsulate robot commands. At the head of
the hierarchy is an abstract Command class. Distributed across the hierarchy is an
execute() operation. The interpreter performs the same role as an API (application
programming interface) but lets you create new machine programs at runtime. Figure 25.1
shows the commands that the robot interpreter supports.

Free download pdf