Here is a summary of the ** Interpreter pattern ** in the GoF design pattern.
--The English word Interpreter means ** interpreter **. ――The Interpreter pattern is a method that ** analyzes and expresses the contents of a file written in some format with a program that acts as an "interpreter" **. --The GoF design patterns are classified as ** behavioral design patterns **.
A program that parses the language written in a text file. BNF notation is used in the grammar of the language used in the text to be parsed.
<program> ::= program <command list>
<command list> ::= <command>* end
<command> ::= <repeat command> | <primitive command>
<repeat command> ::= repeat <number> <command list>
<primitive command> ::= go | right | left
--<program>
・ ・ ・ The token program is followed by the command column <command list>
・ ・ ・ <command>
・ ・ ・ Either the repeat command <repeat command>
・ ・ ・ The token repeat is followed by the number of repetitions <primitive command>
・ ・ ・ go or right or left.
A class that represents the context for parsing.
Context.java
import java.util.StringTokenizer;
public class Context {
private StringTokenizer tokenizer;
private String currentToken;
public Context(String text) {
tokenizer = new StringTokenizer(text);
nextToken();
}
public String nextToken() {
if (tokenizer.hasMoreTokens()) {
currentToken = tokenizer.nextToken();
} else {
currentToken = null;
}
return currentToken;
}
public String currentToken() {
return currentToken;
}
public void skipToken(String token) throws Exception {
if (!token.equals(currentToken)) {
throw new Exception("Warning: " + token + " is expected, but " + currentToken + " is found.");
}
nextToken();
}
public int currentNumber() throws Exception {
int number = 0;
try {
number = Integer.parseInt(currentToken);
} catch (NumberFormatException e) {
throw new Exception("Warning: " + e);
}
return number;
}
}
A class that is a "node" in the syntax tree.
Node.java
public abstract class Node {
public abstract void parse(Context context) throws Exception;
}
This class corresponds to
ProgramNode.java
// <program> ::= program <command list>
public class ProgramNode extends Node {
private Node commandListNode;
public void parse(Context context) throws Exception {
context.skipToken("program");
commandListNode = new CommandListNode();
commandListNode.parse(context);
}
public String toString() {
return "[program " + commandListNode + "]";
}
}
This class corresponds to
CommandNode.java
// <command> ::= <repeat command> | <primitive command>
public class CommandNode extends Node {
private Node node;
public void parse(Context context) throws Exception {
if (context.currentToken().equals("repeat")) {
node = new RepeatCommandNode();
node.parse(context);
} else {
node = new PrimitiveCommandNode();
node.parse(context);
}
}
public String toString() {
return node.toString();
}
}
This class corresponds to
RepeatCommandNode.java
// <repeat command> ::= repeat <number> <command list>
public class RepeatCommandNode extends Node {
private int number;
private Node commandListNode;
public void parse(Context context) throws Exception {
context.skipToken("repeat");
number = context.currentNumber();
context.nextToken();
commandListNode = new CommandListNode();
commandListNode.parse(context);
}
public String toString() {
return "[repeat " + number + " " + commandListNode + "]";
}
}
This class corresponds to
CommandListNode.java
import java.util.ArrayList;
// <command list> ::= <command>* end
public class CommandListNode extends Node {
private ArrayList list = new ArrayList();
public void parse(Context context) throws Exception {
while (true) {
if (context.currentToken() == null) {
throw new Exception("Missing 'end'");
} else if (context.currentToken().equals("end")) {
context.skipToken("end");
break;
} else {
Node commandNode = new CommandNode();
commandNode.parse(context);
list.add(commandNode);
}
}
}
public String toString() {
return list.toString();
}
}
This class corresponds to
PrimitiveCommandNode.java
// <primitive command> ::= go | right | left
public class PrimitiveCommandNode extends Node {
private String name;
public void parse(Context context) throws Exception {
name = context.currentToken();
context.skipToken(name);
if (!name.equals("go") && !name.equals("right") && !name.equals("left")) {
throw new Exception(name + " is undefined");
}
}
public String toString() {
return name;
}
}
The text to be parsed.
program.txt
program end
program go end
program go right go right go right go right end
program repeat 4 go right end end
program repeat 4 repeat 3 go right go left end right end end
This class performs the main processing.
Main.java
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("program.txt"));
String text;
while ((text = reader.readLine()) != null) {
System.out.println("text = \"" + text + "\"");
Node node = new ProgramNode();
node.parse(new Context(text));
System.out.println("node = " + node);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
text = "program end"
node = [program []]
text = "program go end"
node = [program [go]]
text = "program go right go right go right go right end"
node = [program [go, right, go, right, go, right, go, right]]
text = "program repeat 4 go right end end"
node = [program [[repeat 4 [go, right]]]]
text = "program repeat 4 repeat 3 go right go left end right end end"
node = [program [[repeat 4 [[repeat 3 [go, right, go, left]], right]]]]
The Interpreter pattern makes it easy to add or change rules. One of the characteristics of the Interpreter pattern is that "one rule is represented by one class". In other words, if you want to add a new rule, all you have to do is add a subclass of the Node class. Also, if you modify the rule, you only need to modify the subclass of the Node class.
-** GoF design pattern summary **
This article and sample program were created based on the following books.
-** Introduction to design patterns learned in Java language **
It was very easy to understand and I learned a lot. Thank you. The detailed explanations of the design patterns and sample programs are written, so please take a look at the books as well.
Recommended Posts