File tree Expand file tree Collapse file tree 5 files changed +103
-0
lines changed
src/designpattern/interpreter Expand file tree Collapse file tree 5 files changed +103
-0
lines changed Original file line number Diff line number Diff line change 1+ package designpattern .interpreter ;
2+
3+ /**
4+ * 声明一个抽象的解释操作,这个接口为抽象语法树中所有的节点所共享
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ public abstract class AbstractExpression {
10+
11+ public abstract void interpret (Context context );
12+ }
Original file line number Diff line number Diff line change 1+ package designpattern .interpreter ;
2+
3+ /**
4+ * 包含解释器之外的一些全局信息
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ public class Context {
10+
11+ private String input ;
12+ private String output ;
13+
14+ public String getInput () {
15+ return input ;
16+ }
17+
18+ public void setInput (String input ) {
19+ this .input = input ;
20+ }
21+
22+ public String getOutput () {
23+ return output ;
24+ }
25+
26+ public void setOutput (String output ) {
27+ this .output = output ;
28+ }
29+
30+ }
Original file line number Diff line number Diff line change 1+ package designpattern .interpreter ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+
6+ /**
7+ * 构建表示该文法定义的语言中一个特定的句子的抽象语法树,调用解释操作
8+ *
9+ * @author liu yuning
10+ *
11+ */
12+ public class InterpreterClient {
13+ public static void main (String [] args ) {
14+ Context context = new Context ();
15+ List <AbstractExpression > list = new ArrayList <AbstractExpression >();
16+
17+ list .add (new TerminalExpression ());
18+ list .add (new NonTerminalExpression ());
19+ list .add (new TerminalExpression ());
20+ list .add (new TerminalExpression ());
21+
22+ for (AbstractExpression expression : list ) {
23+ expression .interpret (context );
24+ }
25+
26+ }
27+
28+ }
Original file line number Diff line number Diff line change 1+ package designpattern .interpreter ;
2+
3+ /**
4+ * 非终结符表达式,为文法中的非终结符实现解释操作。对文法中每一条规则R1、R2 ... ... Rn都需要一个具体的非终结符表达式类。
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ public class NonTerminalExpression extends AbstractExpression {
10+
11+ @ Override
12+ public void interpret (Context context ) {
13+ System .out .println ("非终端解释器" );
14+ }
15+
16+ }
Original file line number Diff line number Diff line change 1+ package designpattern .interpreter ;
2+
3+ /**
4+ * 实现与文法中的终结符相关联的解释操作,文法中每一个终结符都有一个具体终结表达式与之相对应
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ public class TerminalExpression extends AbstractExpression {
10+
11+ @ Override
12+ public void interpret (Context context ) {
13+ System .out .println ("终端解释器" );
14+
15+ }
16+
17+ }
You can’t perform that action at this time.
0 commit comments