经典的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.
|
Interpreter模式的一个替代品
最新推荐文章于 2023-05-13 16:22:30 发布