设计模式——解释器模式

名称 Interpreter
结构  
意图 给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
适用性
  • 当有
     1// Interpreter
     2
     3// Intent: "Given a language, define a representation for its grammar along 
     4// with an interpreter that uses the representation to interpret 
     5// sentences in the language". 
     6
     7// For further information, read "Design Patterns", p243, Gamma et al.,
     8// Addison-Wesley, ISBN:0-201-63361-2
     9
    10/* Notes:
    11 * This is used to implement a language using a class hierarchy 
    12 */

    13 
    14namespace Interpreter_DesignPattern
    15{
    16    using System;
    17    using System.Collections;
    18
    19    class Context 
    20    {
    21        
    22    }

    23
    24    abstract class AbstractExpression 
    25    {
    26        abstract public void Interpret(Context c);
    27    }

    28
    29    // class for terminal symbol
    30    class TerminalExpression : AbstractExpression
    31    {
    32        override public void Interpret(Context c)    
    33        {
    34            
    35        }

    36    }

    37
    38    // class for grammar rule (one per rule needed)
    39    class NonterminalExpression : AbstractExpression
    40    {
    41        override public void Interpret(Context c)    
    42        {
    43            
    44        }
        
    45    }

    46    // to extend grammar, just add other NonterminalExpression classes
    47
    48    /// <summary>
    49    ///    Summary description for Client.
    50    /// </summary>

    51    public class Client
    52    {
    53        public static int Main(string[] args)
    54        {
    55            Context c = new Context();
    56            ArrayList l = new ArrayList(); //really need a tree here!
    57
    58            // build up context information 
    59            // . . .
    60
    61            // Populate abstract syntax tree with data
    62            l.Add(new TerminalExpression());
    63            l.Add(new NonterminalExpression());
    64
    65            // interpret
    66            foreach (AbstractExpression exp in l)
    67            {
    68                exp.Interpret(c);
    69            }

    70                    
    71            return 0;
    72        }

    73    }

    74}

    75
    76
    一个语言需要解释执行, 并且你可将该语言中的句子表示为一个抽象语法树时,可使用解释器模式。而当存在以下情况时该模式效果最好:
  • 该文法简单对于复杂的文法, 文法的类层次变得庞大而无法管理。此时语法分析程序生成器这样的工具是更好的选择。它们无需构建抽象语法树即可解释表达式, 这样可以节省空间而且还可能节省时间。
  • 效率不是一个关键问题最高效的解释器通常不是通过直接解释语法分析树实现的, 而是首先将它们转换成另一种形式。例如,正则表达式通常被转换成状态机。但即使在这种情况下, 转换器仍可用解释器模式实现, 该模式仍是有用的。
Code Example
posted @ 2005-08-02 08:26  DarkAngel  阅读(704)  评论(1编辑  收藏  举报