:解释模式:定义给定的语言,定义语法的表示,以及利用该表示来定义解释语言中的语句的解释器。
结构图:
AbstractExpression解释器架构抽象类
packageding.study.design patterns.interpreter;
//*
解释器模式抽象类
-声明抽象internet方法,抽象语法树中的所有节点都必须实现此抽象方法。
* @author daniel
*
*/
abstractclassabstractexpression {
//解释方法
公共上下文关联(context context );
}
上下文解释器以外的全局信息
packageding.study.design patterns.interpreter;
//*
非解释程序全局信息
* Interpreter方法所需信息的容器。 此信息全局显示给Interpreter。 充当一些AbstractExpresssion
*实例之间的通信通道。
*
* @author daniel
*
*/
公共类上下文{
私有字符串输入;
私有字符串输出;
//*
* @return the output
*/
公共字符串获取输出
返回输出;
}
//*
* @param output
* the output to set
*/
公共输出(string output )。
this.output=output;
}
//*
* @return the input
*/
公共字符串获取输入
返回输入;
}
//*
* @param input
* the input to set
*/
公共设置输入(string input )。
this.input=input;
}
}
非终端解释器
packageding.study.design patterns.interpreter;
//*
*非终端解释器实现了AbstractExpression
*用于处理语法树中非末端节点语法的接口类。 包含对以下abstractexpression(s )的引用,并调用每个子节点的internet方法:
*
* @author daniel
*
*/
publicclassnonterminalexpressionextendsabstractexpression {
@Override
公共语音输入(上下文上下文) {
System.out.println (非终端解释器);
}
}
终端快速终端解释器
packageding.study.design patterns.interpreter;
//*
终端解释器
-实现与语法中的终结符相关联的internet方法。
-每个语句的最后一个符号必须有一个TerminalExpression实例。
* @author daniel
*
*/
publicclassterminalexpressionextendsabstractexpression {
@Override
公共语音输入(上下文上下文) {
System.out.println (终端解释器);
}
}
客户端ZTestMain
packageding.study.design patterns.interpreter;
import java.util.ArrayList;
import java.util.List;
//*
*解释器模式(interpreter ) :提供语言,定义语法的表示形式,并使用该表示形式定义解释语言中语句的解释器。
*
*输出:
终端解释器
非终端解释器
终端解释器
终端解释器
*
* @author daniel
* @email 576699909@qq.com
* @time 2016-5-31下午2:16:37
*/
public class ZTestMain {
//*
* @param args
*/
publicstaticvoidmain (字符串[ ] args ) {
上下文上下文=new上下文(;
List list=new ArrayList (;
list.add(newterminalexpression ) );
list.add (newnonterminalexpression () );
list.add(newterminalexpression ) );
list.add(newterminalexpression ) );
abstractexpressionexp :列表{
exp.interpret (上下文;
}
}
}
执行结果
源代码