interpreter

GoF Definition:

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

概念

建立一个解释器,对于特定的计算机程序设计语言,用来解释预先定义的文法。简单地说,解释器模式是一种简单的语法解释器构架。

例子

编程语言的解释器。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
public interface  {
void interpret(Context context);
}

public class IntToWords implements {
private String s;

public IntToWords(String s) {
this.s = s;
}


public void interpret(Context context) {
context.printInWords(s);
}
}

public class StringToBinaryExp implements {
private String s;

public StringToBinaryExp(String s) {
this.s = s;
}


public void interpret(Context context) {
context.getBinaryForm(s);
}
}

public class Context {
public String input;

public Context(String input) {
this.input = input;
}

public void getBinaryForm(String input) {
int i = Integer.parseInt(input);
String binaryString = Integer.toBinaryString(i);
System.out.print("Binary equivalent of " + input + " is " + binaryString);
}

public void printInWords(String input) {
this.input = input;
System.out.print("Printing the input in words:");
char[] c = input.toCharArray();
for (int i = 0; i < c.length; ++i) {
switch (c[i]) {
case '1':
System.out.print("One ");
break;
case '2':
System.out.print("Two ");
break;
case '3':
System.out.print("Three ");
break;
case '4':
System.out.print("Four ");
break;
case '5':
System.out.print("Five ");
break;
case '6':
System.out.print("Six ");
break;
case '7':
System.out.print("Seven ");
break;
case '8':
System.out.print("Eight ");
break;
case '9':
System.out.print("Nine ");
break;
case '0':
System.out.print("Ten");
break;
default:
System.out.print("# ");
break;
}
}
}
}