Definition: The interpreter pattern builds an interpreter for a language.
Usage: Use the interpreter pattern to convert a language into another form. It can converted into another language, a set of objects within the program, or even into a program itself. It also can be executed one line at a time.
enum AiAction {JUMP, MOVE_LEFT, MOVE_RIGHT}
class Interpreter {
static ArrayList interpret(String text) {
String[] aTextLine = split text up at each newline
ArrayList aAiAction = new ArrayList();
for(int iTextLine = 0; iTextLine < aTextLine.length; iTextLine++) {
String line = aTextLine[iTextLine]
if(line.equalsIgnoreCase("jump"))
aAiAction.add(AiAction.JUMP);
else if(line.equalsIgnoreCase("move left"))
aAiAction.add(AiAction.MOVE_LEFT);
else if(line.equalsIgnoreCase("move right"))
aAiAction.add(AiAction.MOVE_RIGHT);
else
output an error
}
return aAiAction;
}
}
The purpose of this interpreter is to cause a computer-controlled sprite to take various actions from a list of actions.
This is a simple and very ugly example of the interpreter design pattern. A more realistic example would span several classes and be much too complex. It is important to read a book about compilers and interpreters if you want to program a professional quality interpreter.
Copyright (C) 2008-2009 Steven Fletcher. All rights reserved.