1. 程式人生 > 實用技巧 >直譯器模式

直譯器模式

定義一個語言的文法,並且建立一個直譯器來解釋該語言中的句子,“語言”是指使用規定格式和語法的程式碼。

其中,Context類用於儲存直譯器之外的一些全域性資訊;NumberNode類稱作終結符表示式;SymbolNode類稱作非終結符表示式;非終結符表示式中包含其他非終結符表示式或終結符表示式,非終結符表示式中的interpret方法通常以遞迴方式執行。

public interface Node {
    Float interpret(Context context);
}
 
public class NumberNode implements Node {
    
private String key; public NumberNode(String key) { this.key = key; } @Override public Float interpret(Context context) { return context.getNode().get(key); } } public class SymbolNode implements Node { private Node leftNode; private Node rightNode;
private String symbol; public SymbolNode(Node leftNode, Node rightNode, String symbol) { this.leftNode = leftNode; this.rightNode = rightNode; this.symbol = symbol; } @Override public Float interpret(Context context) { switch (this.symbol) {
case "+": return leftNode.interpret(context) + rightNode.interpret(context); case "-": return leftNode.interpret(context) - rightNode.interpret(context); case "*": return leftNode.interpret(context) * rightNode.interpret(context); case "/": return leftNode.interpret(context) / rightNode.interpret(context); default: return null; } } } public class Context { private String text; private Map<String, Float> node; public Context(String text) { this.text = text; node = new LinkedHashMap<>(); } public String getText() { return text; } public void setText(String text) { this.text = text; } public Map<String, Float> getNode() { return node; } public void interpret() { String[] split = text.split(" "); for (String textSplit : split) { if (!"+".equals(textSplit) && !"-".equals(textSplit) && !"*".equals(textSplit) && !"/".equals(textSplit)) { node.put(textSplit, new Random().nextFloat()); } } Node leftNode = null; Node rightNode = null; LinkedList<Node> nodeList = new LinkedList<Node>(); nodeList.push(new NumberNode(split[0])); for (int i = 1; i < split.length; i++) { if ("+".equals(split[i]) || "-".equals(split[i]) ||"*".equals(split[i]) || "/".equals(split[i])) { leftNode = nodeList.pop(); rightNode = new NumberNode(split[i + 1]); nodeList.push(new SymbolNode(leftNode, rightNode, split[i])); } } System.out.println(nodeList.pop().interpret(this)); } } @Test public void interpreterTest() { Context context = new Context("number1 * number2 / number3 + number4 - number5"); context.interpret(); }

轉載於:https://blog.csdn.net/sinat_32787481/article/details/83448951