一,模式定義
二,模式結構
三,模式執行個體
四,模式應用
一,定義:解釋器模式就是自定義一套文法規範,用于解釋語句
二,
,
三,先定義一個抽象表達式類Node.javapackage com.lts.interpret;
//定義抽象表達式類
public interface Node {
public int interpret();//解釋方法
}
分别定義一個終結符表達式類ValueNode和非終結符表達式類SymbolNode實作該接口
package com.lts.interpret;
//定義終結符表達式類
public class ValueNode implements Node{
private int value;
public ValueNode(int value)
{
this.value=value;
}
public int interpret(){
return this.value;
}
}
package com.lts.interpret;
//定義非終結符表達式類
public abstract class SymbolNode implements Node{
protected Node left;
protected Node right;
public SymbolNode(Node left,Node right){
this.left=left;
this.right=right;
}
}
在SymbolNode下定義三個子類MulNode,DivNode和ModNode分别實作乘法,除法和求餘的功能
package com.lts.interpret;
//乘法類繼承非終結符表達式類
public class MulNode extends SymbolNode{
public MulNode(Node left,Node right){
super(left,right);
}
public int interpret(){
return super.left.interpret()*super.right.interpret();
}
}
package com.lts.interpret;
//除法類繼承非終結符表達式類
public class DivNode extends SymbolNode{
public DivNode(Node left,Node right){
super(left,right);
}
public int interpret(){
return super.left.interpret()/super.right.interpret();
}
}
package com.lts.interpret;
//求模類繼承非終結符表達式類
public class ModNode extends SymbolNode{
public ModNode(Node left,Node right){
super(left,right);
}
public int interpret(){
return super.left.interpret()%super.right.interpret();
}
}
最後定義一個解釋器類Calculator用于封裝解釋器的功能
package com.lts.interpret;
import java.util.*;
public class Calculator {
private String statement;
private Node node;
public void build(String statement){
Node left=null,right=null;
Stack stack=new Stack();
String[] statementArr=statement.split(" ");//把字元串分割成字元串數組
for(int i=0;i<statementArr.length;i++){
if(statementArr[i].equalsIgnoreCase("*")){
left=(Node)stack.pop();
int val=Integer.parseInt(statementArr[++i]);
right=new ValueNode(val);
stack.push(new MulNode(left,right));
}
else if(statementArr[i].equalsIgnoreCase("/")){
left=(Node)stack.pop();
int val=Integer.parseInt(statementArr[++i]);
right=new ValueNode(val);
stack.push(new DivNode(left,right));
}
else if(statementArr[i].equalsIgnoreCase("%"))
{
left=(Node)stack.pop();
int val=Integer.parseInt(statementArr[++i]);
right=new ValueNode(val);
stack.push(new ModNode(left,right));
}
else{
stack.push(new ValueNode(Integer.parseInt(statementArr[i])));
}
}
this.node=(Node)stack.pop();
}
public int compute(){
return node.interpret();
}
}
在用戶端做測試
package com.lts.interpret;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
String statement="3 * 4 / 2 % 4";
Calculator calculator=new Calculator();
calculator.build(statement);
int result=calculator.compute();
System.out.println(statement+"="+result);
}
}
運作結果:
四,模式應用:
優點:易于修改和拓展文法,修改文法隻需在對應的類上修改,拓展文法隻需要增加對應的類即可
缺點:執行效率較低,在調用compute方法裡的interpret()時,Node下的所有子類的interpret方法也會遞歸執行,降低了效率,同時應用場景有限
總結:解釋器模式适用于對程式運作效率要求不高,表達式文法簡單的情況。如編譯器和科學電腦等