大B:“來舉一個加減乘除的例子吧,實現(xiàn)思路來自於《java與模式》中的例子。每個角色的功能按照上面提到的規(guī)範(fàn)來實現(xiàn)。”
//上下文(環(huán)境)角色,使觓shMap來存儲變量對應(yīng)的數(shù)值
classContext
{
privateMapvalueMap=newHashMap();
publicvoidaddValue(Variablex,inty)
{
Integeryi=newInteger(y);
valueMap.put(x,yi);
}
publicintLookupValue(Variablex)
{
inti=((Integer)valueMap.get(x)).intValue();
returni;
}
}
//抽象表達式角色,也可以用接口來實現(xiàn)
abstractclassEXPression
{
publicabstractintinterpret(Contextcon);
}
//終結(jié)符表達式角色
classConstantextendsExpression
{
privateinti;
publicConstant(inti)
{
this.i=i;
}
publicintinterpret(Contextcon)
{
returni;
}
}
classVariableextendsExpression
{
publicintinterpret(Contextcon)
{
//this爲(wèi)調(diào)用interpret方法的Variable對象
returncon.LookupValue(this);
}
}
//非終結(jié)符表達式角色
classAddextendsExpression
{
privateExpressionleft,right;
publicAdd(Expressionleft,Expressionright)
{
this.left=left;
this.right=right;
}
publicintinterpret(Contextcon)
{
returnleft.interpret(con)+right.interpret(con);
}
}
classSuBTractextendsExpression
{
privateExpressionleft,right;
publicSubtract(Expressionleft,Expressionright)
{
this.left=left;
this.right=right;
}
publicintinterpret(Contextcon)
{
returnleft.interpret(con)-right.interpret(con);
}
}
classMultiplyextendsExpression
{
privateExpressionleft,right;
publicMultiply(Expressionleft,Expressionright)
{
this.left=left;
this.right=right;
}
publicintinterpret(Contextcon)
{
returnleft.interpret(con)*right.interpret(con);
}
}
classDivisionextendsExpression
{
privateExpressionleft,right;
publicDivision(Expressionleft,Expressionright)
{
this.left=left;
this.right=right;
}
publicintinterpret(Contextcon)
{
try{
returnleft.interpret(con)/right.interpret(con);
}catch(ArithmeticExceptionae)
{
System.out.println(“被除數(shù)爲(wèi)0!”);
return-11111;
}
}
}
//測試程序,計算(a*b)/(a-b+2)
publicclassTest
{
privatestaticExpressionex;
privatestaticContextcon;
publicstaticvoidmain(String[]args)
{
con=newContext();
//設(shè)置變量、常量
Variablea=newVariable();
Variableb=newVariable();
Constantc=newConstant(2);
//爲(wèi)變量賦值
con.addValue(a,5);
con.addValue(b,7);
//運算,對句子的結(jié)構(gòu)由我們自己來分析,構(gòu)造
ex=newDivision(newMultiply(a,b),newAdd(newSubtract(a,b),c));
System.out.println(運算結(jié)果爲(wèi):+ex.interpret(con));
}
}
大B:“解釋器模式並沒有說明如何創(chuàng)建一個抽象語法樹,因此它的實現(xiàn)可以多種多樣,在上面我們是直接在Test中提供的,當(dāng)然還有更好、更專業(yè)的實現(xiàn)方式。對於終結(jié)符,建議採用享元模式來共享它們的拷貝,因爲(wèi)它們要多次重複出現(xiàn)。但是考慮到享元模式的使用侷限性,建議還是當(dāng)你的系統(tǒng)中終結(jié)符重複的足夠多的時候再考慮享元模式?!?