Java Reference
In-Depth Information
The expressions are reusable for other purposes. You can add methods to the Expression to increase the
functionality of the expressions. To add more flexibility, use the Visitor pattern, which lets you dynamically
change the interpret method. (See “ Visitor ” on page 121.)
It might be difficult to create the abstract syntax tree—it isn't defined by the Interpreter pattern. The Interpreter
assumes the syntax tree has been created somewhere, somehow.
Pattern Variants
The original pattern as described in the GoF Design Patterns book uses an abstract class instead of an interface.
As stated before, we recommend that you use interfaces wherever possible, unless a partial implementation
should be supplied.
Related Patterns
Related patterns include the following:
Composite (page 157) - The structure for interpreted expressions is based on the composite pattern, using
terminal expressions (leaf nodes) and nonterminal expressions (branch nodes).
Flyweight (page 183) - To reduce the number of redundant or similar objects, you can apply the Flyweight
pattern to some of the Expressions .
Iterator (page 69) - Iterator is used to iterate through the abstract syntax tree and its nodes.
Visitor (page 121) - When a Visitor pattern is used, the Interpreter gains flexibility.
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a RunPattern class,
see “ Interpreter ” on page 381 of the “ Full Code Examples ” appendix.
The Expression hierarchy is at the heart of the Interpreter pattern. It defines the grammar that can be used to
create and evaluate expressions. The Expression interface is the foundation for all expressions, and defines the
interpret method that performs an evaluation.
Table 2-1 lists the interface and corresponding information.
Table 2-1. Purpose of the Expression interface and its implementers
Expression
Common interface for all expressions
ConstantExpression
Represents a constant value
VariableExpression
Represents a variable value, obtained by calling a method on some class
CompoundExpression
A pair of comparison expressions that evaluate to a boolean result
AndExpression
The logical “and” of two expressions
OrExpression
The logical “or” of two expressions
ComparisonExpression
A pair of expressions that evaluate to a boolean result
EqualsExpression
P erforms an equals method comparison between the two expressions
ContainsExpression
Checks to see if the first String expression contains the second one
Example 2.8 Expression.java
1. public interface Expression {
2. void interpret(Context c);
3. }
 
Search WWH ::




Custom Search