行为型设计模式-解释器模式

来源:互联网 发布:买房看房用什么软件 编辑:程序博客网 时间:2024/06/05 05:49

解释器模式:

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

解释器模式参与角色:

AbstractExpression:定义解释器的接口,约定解释器的解释操作。其中的Interpret接口,正如其名字那样,
它是专门用来解释该解释器所要实现的功能。(如加法解释器中的Interpret接口就是完成两个操作数的相加功能)。

TerminalExpression:终结符解释器,用来实现语法规则中和终结符相关的操作,不再包含其他的解释器,
如果用组合模式来构建抽象语法树的话,就相当于组合模式中的叶子对象,可以有多种终结符解释器。

NonterminalExpression:非终结符解释器,用来实现语法规则中非终结符相关的操作,
通常一个解释器对应一个语法规则,可以包含其他解释器,如果用组合模式构建抽象语法树的话,
就相当于组合模式中的组合对象。可以有多种非终结符解释器。

Context:上下文,通常包含各个解释器需要的数据或是公共的功能。这个Context在解释器模式中起着非常重要的作用。
一般用来传递被所有解释器共享的数据,后面的解释器可以从这里获取这些值。

Client:客户端,指的是使用解释器的客户端,通常在这里将按照语言的语法做的表达式转换成使用解释器对象描述的抽象语法树,
然后调用解释操作。

上下文:Context

public class Context {    private String str;    public Context(String str) {        this.str = str;    }    public String getStr() {        return this.str;    }}

解释器:

/** * "我"字符解析器 * @author Yang ZhiWei * */public class WoInterpreter implements AbstractExpression {    public void parse(Context context) {        if (context.getStr().indexOf("我") != -1) {            System.out.print("I");        }    }}
/** * "空白字符"字符解析器 * @author Yang ZhiWei * */public class FuhaoInterpreter implements AbstractExpression {    public void parse(Context context) {        if (context.getStr().indexOf(" ") != -1) {            System.out.print(" ");        }    }}
/** * "爱"字符解析器 * @author Yang ZhiWei * */public class AiInterpreter implements AbstractExpression {    public void parse(Context context) {        if (context.getStr().indexOf("爱") != -1) {            System.out.print("Love");        }    }}
/** * "你"字符解析器 * @author Yang ZhiWei * */public class NiInterpreter implements AbstractExpression {    public void parse(Context context) {        if (context.getStr().indexOf("你") != -1) {            System.out.print("you");        }    }}

测试代码:

 Context context = new Context("我 爱 你");/*** 字符解析器集合:按照顺序进行解析*/List<AbstractExpression> list = new ArrayList<AbstractExpression>();list.add(new WoInterpreter());list.add(new FuhaoInterpreter());list.add(new AiInterpreter());list.add(new FuhaoInterpreter());list.add(new NiInterpreter());//顺序解析目标对象for (int i = 0; i < list.size(); i++) {AbstractExpression interpreter = (AbstractExpression)list.get(i);interpreter.parse(context);}

效果:
这里写图片描述

0 0