设计模式学习总结8 行为型3 Interpreter解释器模式

Interpreter解释器模式(行为型)

作用

支持语言或符号的指令解释,这些符号精确的以某种语法定义。

The Interpreter pattern supports the interpretation of instructions written in a language or notation defined for a specific purpose. The notation is precise and can be defined in terms of a grammar.

设计

Client,对象的结构,代表特定语法的指令
A class that builds an object structure that represents a set of instructions in the given grammar
Context,包含解释器所需的信息(输入或输出)
A class that contains information for use by the Interpreter (usually its input and output)
Term,表达式抽象类,提供解释器的缺省操作和所有类的接口
An abstract class that provides an interface for all the classes in the structure and a default for the Interpreter operation
Nonterminal,非终结表达式,可以包含其它解释器表达式
A class that implements the Interpreter and also can contain other Term instances
Terminal,终结表达式,解释器的实现类
A class that implements the Interpreter

举例

Context,描述规则和图像输出
Terminal,一种特性如Top
Nontermial,标签如TextBox
Interpreter,将XML处理后显示图形界面
实现

using System;
using System.Collections;

class MainApp
{
    
static void Main()
    {
        Context context 
= new Context();

        
// Usually a tree 
        ArrayList list = new ArrayList();

        
// Populate 'abstract syntax tree' 
        list.Add(new TerminalExpression());
        list.Add(
new NonterminalExpression());
        list.Add(
new TerminalExpression());
        list.Add(
new TerminalExpression());

        
// Interpret 
        foreach (AbstractExpression exp in list)
        {
            exp.Interpret(context);
        }

        
// Wait for user 
        Console.Read();
    }
}

// "Context" 
class Context
{
}

// "AbstractExpression" 
abstract class AbstractExpression
{
    
public abstract void Interpret(Context context);
}

// "TerminalExpression" 
class TerminalExpression : AbstractExpression
{
    
public override void Interpret(Context context)
    {
        Console.WriteLine(
"Called Terminal.Interpret()");
    }
}

// "NonterminalExpression" 
class NonterminalExpression : AbstractExpression
{
    
public override void Interpret(Context context)
    {
        Console.WriteLine(
"Called Nonterminal.Interpret()");
    }
}

应用场景

当你有一套语法需要解释
1、语法简洁
2、不太注重效率
3、已有分析语法的工具
4、xml是语法规范的一种选择

Use the Interpreter pattern when…
You have a grammar to be interpreted and:
•  The grammar is not too large.
•  Efficiency is not critical.
•  Parsing tools are available.
•  XML is an option for the specification.

总结

在软件的构建过程中,如果某一特定领域的问题比较复杂,类似的模式不断重复出现,如果使用普通的编程方式来实现将面临非常频繁的变化。
这种情况下,将特定领域的问题表达为某种句法规则下的表达式,然后构建一个解释器来解释这个表达式,从而达到解决问题的目的。

《设计模式》GoF中的定义:给定一个表达式,定义了这个表达式的语法,并定义解释器,这个解释器使用它的语法来解释表达式的意义。
Interpreter模式的几个要点:
应用的场合:“业务规则频繁变化,且类似模式不断重复出现,规则容易抽象成语法规则”
有了语法规则,就可以使用面向对象的技巧来方便的扩展语法
Interpreter模式比较适合简单的语法,对于复杂的语法Interpreter模式要求比较复杂的类结构,需要语法分析生成器。

原文地址:https://www.cnblogs.com/utopia/p/1679452.html