Known Uses
The Interpreter pattern is widely used in compilers implemented
withobject-oriented languages, as the Smalltalk compilers are. SPECTalkuses the
pattern to interpret descriptions of input fileformats [Sza92]. The QOCA
constraint-solving toolkituses it to evaluate constraints [HHMV92].
Considered in its most general form (i.e., an operation distributedover a class
hierarchy based on the Composite pattern), nearly everyuse of the Composite pattern
will also contain the Interpreterpattern. But the Interpreter pattern should be
reserved for thosecases in which you want to think of the class hierarchy as defining
alanguage.
Design Patterns: Elements of Reusable Object-Oriented Software
288
Related Patterns
Composite (183):The abstract syntax tree is an instance of the Composite pattern.
Flyweight (218) shows how to share terminal symbols within the abstract syntaxtree.
Iterator (289):The interpreter can use an Iterator to traverse the structure.
Visitor (366) canbe used to maintain the behavior in each node in the abstract
syntaxtree in one class.
1
For simplicity, we ignore operator precedence andassume it's the responsibility
of whichever object constructs thesyntax tree.
Design Patterns: Elements of Reusable Object-Oriented Software
289
Iterator
Intent
Provide a way to access the elements of an aggregate objectsequentially without
exposing its underlying representation.
Also Known As
Cursor
Motivation
An aggregate object such as a list should give you a way to access itselements
without exposing its internal structure. Moreover, you mightwant to traverse the
list in different ways, depending on what youwant to accomplish. But you probably
don't want to bloat the Listinterface with operations for different traversals,
even if you couldanticipate the ones you will need. You might also need to have
more thanone traversal pending on the same list.
The Iterator pattern lets you do all this. The key idea in thispattern is to take
the responsibility for access and traversal out ofthe list object and put it into
an
iterator
object. TheIterator class defines an interface for accessing the list's
elements.An iterator object is responsible for keeping track of the currentelement;
that is, it knows which elements have been traversed already.
For example, a List class would call for a ListIterator with thefollowing
relationship between them:
Before you can instantiate ListIterator, you must supply the List totraverse.
Once you have the ListIterator instance, you can access thelist's elements
sequentially. The CurrentItem operation returns thecurrent element in the list,
First initializes the current element tothe first element, Next advances the
Do'stlaringiz bilan baham: |