设计模式 解释器模式(Interpreter Parttern)

意图

  给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

适用性

  1.当有一个语言需要解释执行, 并且你可将该语言中的句子表示为一个抽象语法树时,可使用解释器模式。而当存在以下情况时该模式效果最好。

  2.该文法简单对于复杂的文法, 文法的类层次变得庞大而无法管理。此时语法分析程序生成器这样的工具是更好的选择。它们无需构建抽象语法树即可解释表达式, 这样可以节省空间而且还可能节省时间。 

  3.效率不是一个关键问题最高效的解释器通常不是通过直接解释语法分析树实现的, 而是首先将它们转换成另一种形式。例如,正则表达式通常被转换成状态机。但即使在这种情况下, 转换器仍可用解释器模式实现, 该模式仍是有用的。

结构图

Code

 1 // Interpreter
2
3 /* Notes:
4 * This is used to implement a language using a class hierarchy
5 */
6
7 namespace Interpreter_DesignPattern
8 {
9 using System;
10 using System.Collections;
11
12 class Context
13 {
14
15 }
16
17 abstract class AbstractExpression
18 {
19 abstract public void Interpret(Context c);
20 }
21
22 // class for terminal symbol
23 class TerminalExpression : AbstractExpression
24 {
25 override public void Interpret(Context c)
26 {
27
28 }
29 }
30
31 // class for grammar rule (one per rule needed)
32 class NonterminalExpression : AbstractExpression
33 {
34 override public void Interpret(Context c)
35 {
36
37 }
38 }
39 // to extend grammar, just add other NonterminalExpression classes
40
41 /// <summary>
42 /// Summary description for Client.
43 /// </summary>
44 public class Client
45 {
46 public static int Main(string[] args)
47 {
48 Context c = new Context();
49 ArrayList l = new ArrayList(); //really need a tree here!
50
51 // build up context information
52 // . . .
53
54 // Populate abstract syntax tree with data
55 l.Add(new TerminalExpression());
56 l.Add(new NonterminalExpression());
57
58 // interpret
59 foreach (AbstractExpression exp in l)
60 {
61 exp.Interpret(c);
62 }
63
64 return 0;
65 }
66 }
67 }



人生如棋、我愿为卒、行动虽缓、从未退过

原文地址:https://www.cnblogs.com/sunjinpeng/p/2437685.html