Home  >  Article  >  Java  >  Sample code for implementing the Interpreter mode in Java

Sample code for implementing the Interpreter mode in Java

黄舟
黄舟Original
2017-03-11 11:43:402374browse

Sample code for Java implementation of interpreter mode

/**
 * 声明一个抽象的解释操作
 * @author stone
 *
 */
public interface Interpreter {
	
	public void interpret(Context context);  //实际中,可以有个返回的类型,定义解释出的数据对象
}
public class XmlSaxInterpreter implements Interpreter {

	@Override
	public void interpret(Context context) {
		System.out.println("xml sax Interpreter:" + context.getData());
	}

}
public class XmlDomInterpreter implements Interpreter {

	@Override
	public void interpret(Context context) {
		System.out.println("xml dom Interpreter:" + context.getData());
	}

}
/**
 * 包含解释器之外的一些信息
 * @author stone
 *
 */
public class Context {
	private String data;
	
	public String getData() {
		return data;
	}
	
	public void setData(String data) {
		this.data = data;
	}
}
/*
 * 解释器(Interpreter)模式
 * 给定一门语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中句子。 属于行为型模式
 * 应用场合,如编译器、正则表达式、语言规范...
 * 解释器模式在实际的系统开发中使用的非常少,因为它会引起效率、性能以及维护等问题,
 */
public class Test {
	public static void main(String[] args) {
		Context context = new Context();
		context.setData("一段xml数据");
		new XmlSaxInterpreter().interpret(context);
		new XmlDomInterpreter().interpret(context);
	}
}

The above is the detailed content of Sample code for implementing the Interpreter mode in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn