Interpreter模式的一个替代品

经典的23模式中,应该数interpreter最难了吧。偏偏不走运,在一个应用中必须实现一个表达式运算,解释一个字符串,算出它的值出来。按说应该用interpreter,可是挺难实现的;找了网上的一些范例,都有很多限制,或者干脆算错了。
不过,琢磨着现在脚本语言不停地要嵌入主流语言,他们应该都有解释器吧?顺手找来 Jypthon,一下就发现了它的解释器,现成的,下面就是我的一个简单实现:
/*
 * Created on 2005-7-6
 *
 */
package manager;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class StatementCompute {
 PythonInterpreter interpreter = new PythonInterpreter();
 //private static PyInteger true_value = null;
 private static PyInteger false_value = null;
 public StatementCompute() {
  //true_value = new PyInteger(1);
  false_value = new PyInteger(0);
 }
 private PyObject calculate(String statement) {
  interpreter.cleanup();
  String toBeC = "x = "+statement;
  try{
   interpreter.exec(toBeC);
  }catch(Exception e){
   return false_value;
  }
  return (PyObject) interpreter.get("x");
 }
 public String calculateStringStatement(String statement){
  return calculate(statement).toString();
 }
 public String calculateBoolStatement(String statement){
  String s = preDealBoolStatement(statement);
  if(((PyInteger)calculate(s)).getValue()==1){
   return "true";
  }else{
   return "false";
  }
 }
 private String preDealBoolStatement(String statement){
    
  String s = statement.toLowerCase();
  s = s.replaceAll("true","1");
  s = s.replaceAll("false", "0");
  return s;
  
 }
 public static void main(String[] args){
  StatementCompute sc = new StatementCompute();
  System.out.println(sc.calculateBoolStatement("True or false").toString());
  System.out.println(sc.calculateStringStatement("3*5+3").toString());
 }
}
要让它运行起来,需要在classpath中加上jython.jar.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值