Design Patterns Java™ Workbook

(Michael S) #1
Chapter 25. Interpreter

CHALLENGE 25.2


Write the code for WhileCommand.java.

You might put your WhileCommand class into use with an interpreter that unloads a star
press:


package com.oozinoz.robot.interpreter;
import com.oozinoz.machine.*;
public class ShowWhile
{
public static void main(String[] args)
{
Context c = MachineLine.createContext();
Constant sp =
new Constant(c.lookup("StarPress1401"));
Constant ub =
new Constant(c.lookup("UnloadBuffer1501"));
WhileCommand wc =
new WhileCommand(
new HasMaterial(sp),
new CarryCommand(sp, ub));
wc.execute(c);
}
}


The wc object is an interpreter that interprets execute() to mean unload all the bins from
star press 1401.


The machine command interpreter hierarchy lets you create arbitrary programs at runtime by
composing new interpreter objects. In this regard, INTERPRETER is similar to COMMAND.


CHALLENGE 25.3


What is the difference, if any, between the COMMAND and INTERPRETER patterns?

Interpreters, Languages, and Parsers....................................................................................................


The INTERPRETER pattern addresses how interpreters work but does not specify how you
should compose new interpreters at runtime. In this chapter, you have built new interpreters
"manually," by writing lines of Java code. But by far the most common way to create a new
interpreter is with a parser. A parser can read textual commands from a file or from a user
prompt and can use the text to create an interpreter. Powerful! Another reason to learn about
building parsers is that if you want to understand the INTERPRETER chapter in Design
Patterns (Gamma et al. 1995), you really need to understand the interrelation of interpreters,
parsers, and computer languages.

Free download pdf