Design Patterns: Elements of Reusable Object-Oriented Software
273
Coplien describes how to implement
functors
, objects thatare functions, in C++
[Cop92]. He achieves a degree oftransparency in their use by overloading the
function call operator(operator()). The Command pattern is different; its focusis
on maintaining a
binding between
a receiver and a function(i.e., action), not
just maintaining a function.
Related Patterns
A Composite (183)can be used to implement MacroCommands.
A Memento (316)can keep state the command requires to undo its effect.
A command that must be copied before being placed on the historylist acts as a
Prototype (133).
Design Patterns: Elements of Reusable Object-Oriented Software
274
Interpreter
Intent
Given a language, define a represention for its grammar along with aninterpreter
that uses the representation to interpret sentences in thelanguage.
Motivation
If a particular kind of problem occurs often enough, then it might beworthwhile
to express instances of the problem as sentences in asimple language. Then you
can build an interpreter that solves theproblem by interpreting these sentences.
For example, searching for strings that match a pattern is a commonproblem. Regular
expressions are a standard language for specifyingpatterns of strings. Rather
than building custom algorithms to matcheach pattern against strings, search
algorithms could interpret aregular expression that specifies a set of strings
to match.
The Interpreter pattern describes how to define a grammar for simplelanguages,
represent sentences in the language, and interpret thesesentences. In this example,
the pattern describes how to define agrammar for regular expressions, represent
a particular regularexpression, and how to interpret that regular expression.
Suppose the following grammar defines the regular expressions:
expression ::= literal | alternation | sequence | repetition |
'(' expression ')'
alternation ::= expression '|' expression
sequence ::= expression '&' expression
repetition ::= expression '*'
literal ::= 'a' | 'b' | 'c' | ... { 'a' | 'b' | 'c' | ... }*
The symbol expression is the start symbol, and literalis a terminal symbol defining
simple words.
The Interpreter pattern uses a class to represent each grammar rule.Symbols on
the right-hand side of the rule are instance variables ofthese classes. The grammar
above is represented by five classes: anabstract class RegularExpression and its
four subclassesLiteralExpression, AlternationExpression, SequenceExpression,
andRepetitionExpression. The last three classes define variables thathold
subexpressions.
Do'stlaringiz bilan baham: |