Java Reference
In-Depth Information
Interpreter
Pattern Properties
Type: Behavioral
Level: Class
Purpose
To define an interpreter for a language.
Introduction
How do you solve a jigsaw puzzle? An incredibly gifted person might look through all 5,000 pieces and, after
some calculations, know where all the pieces belong.
Members of another school of puzzle-solving thought use a different approach. They sort all the pieces that
belong together in one part of the puzzle, then try to solve that smaller part first. You would try pieces until two
of them match, repeating the process until a small part is finished. Then combine that part with other small pieces,
and on and on until you complete the puzzle and discover you're missing a dozen pieces.
Solving a problem is often done this way; by splitting the problem up into subproblems, recursively. Not only that,
but you have to solve the subproblems as well. When the problems are interdependent, solving them is very
difficult.
The best solution is to create a simple language that describes relationships. Model a complex problem with a
language and solve the sentence that describes the problem. With this approach, you should be able to greatly
simplify the task of obtaining the solution. Like the puzzle, you divide the problem into progressively smaller
parts. You solve the smaller parts, then you combine the solutions to obtain an overall solution. And hope that
when you're done, you won't have any pieces missing.
Applicability
Use Interpreter when:
There is a simple language to interpret.
Recurring problems can be expressed in that language.
Efficiency is not the main issue.
Description
The Interpreter dissects a problem by dividing it into small pieces, then puts these pieces back together as a
sentence in a simple language. The other part of the interpreter uses that sentence to interpret and solve the
problem step by step. This is done by creating an abstract syntax tree.
A well-known example of this approach is a regular expression. Regular expressions are used to describe patterns
for which to search and modify strings, and the language used to describe these patterns is very concise.
Here's some terminology based on a mathematical example. On many occasions you might use certain formulas,
like the Pythagorean Theorem:
(A 2 + B 2 ) = C 2
So here's a simple mathematical formula:
Result = (a + b)/c
result 's value depends on the values for a, b, and c.
 
Search WWH ::




Custom Search