设计模式-行为型- 解释器模式(Interpreter)

定义

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

角色

抽象解释器(AbstractExpression):声明一个抽象解释操作

终结符表达式(TerminalExpression):实现文法中与终结符相关联的解释操作

非终结符表达式(NonterminalExpression):实现了文法中非终结符的解释操作,可用于文法中的连接符、运算符等

上下文/环境(Context):它包含了解释器之外的全局信息

优点

  • 解释器是可以作为一个语法分析工具,扩展性很好,修改语法规则,只需要修改相应的终结符类就可以,如果要修改语法,则修改相应的非终结符类即可

缺点

  • 语法较为复杂时,类太多

适用场景

  • 重复发生的有规律的问题,如加减乘除表达式

类图

Interpreter

package com.vapy.behavior.Interpreter;
/**
 * @author vapy 2016年8月26日
 * 
 * 抽象解释器
 */
public abstract class AbstractExpression {

    public abstract String interpret(String str);
}
package com.vapy.behavior.Interpreter;
/**
 * @author vapy 2016年8月26日
 * 
 * 终结符表达式
 */
public class Move extends AbstractExpression {
    public Move() {
    }

    @Override
    public String interpret(String distance) {
        if(distance.matches("[0-9]*")){
            return "move " + distance + " meters ";
        }
        return "move 0 meter";      //如果不是数据,移动距离算0
    }
}
package com.vapy.behavior.Interpreter;
/**
 * @author vapy 2016年8月26日
 * 
 * 非终结符表达式
 */
public class And extends AbstractExpression {

    public And() {
    }

    @Override
    public String interpret(String and) {
        if(and.equals("and")) {
            return ",and then ";
        }
        return "";
    }
}
package com.vapy.behavior.Interpreter;
/**
 * @author vapy 2016年8月26日
 * 
 * 上下文
 */
public class Context {
    private String input;
    private String output = "";

    public Context(String input) {
        this.input = input;
    }

    public void exec() {
        AbstractExpression move = new Move();
        AbstractExpression and = new And();
        String[] in = input.split(" ");
        for(String str : in) {
            if(str.equalsIgnoreCase("and")) {
                output += and.interpret(str);
            } else {
                output += move.interpret(str);
            }
        }
    }

    public String getOutput() {
        return output;
    }
}
package com.vapy.behavior.Interpreter;
/**
 * @author vapy 2016年8月26日
 */

public class Client {
    public static void main(String[] args) {
        String inputExpr = "22 and 23";
        Context context = new Context(inputExpr);
        context.exec();
        System.out.println(context.getOutput());
    }
}

InterpreterResult
本文代码可在github查看:点击此处

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值