解释器模式
定义:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
优点:容易修改和拓展语法,适用于文法简单并且对处理效率要求低的情况。
缺点:不适用于发杂文法的情况。
使用时机:当有一个语言需要解释执行,并且可将该语言中的句子表示为一个抽象语法树的时候,可以用解释器模式。
下面代码要把“我 爱 你”翻译成为英文,空格也要翻译,正好用上解释器模式。
可以看到这里有四个字符需要翻译,先把公用的翻译接口定义出来
public interface Interpreter {
void parse(Context context);
}
然后是具体的字符翻译类
public class WoInterpreter implements Interpreter {
public void parse(Context context) {
if (context.getStr().indexOf("我") != -1) {
System.out.print("I");
}
}
}
public class AiInterpreter implements Interpreter {
public void parse(Context context) {
if (context.getStr().indexOf("爱") != -1) {
System.out.print("Love");
}
}
}
public class NiInterpreter implements Interpreter {
public void parse(Context context) {
if (context.getStr().indexOf("你") != -1) {
System.out.print("you");
}
}
}
public class FuhaoInterpreter implements Interpreter {
public void parse(Context context) {
if (context.getStr().indexOf(" ") != -1) {
System.out.print(" ");
}
}
}
另外需要一个内容类保存需要翻译的内容
public class Context {
public Context(String str) {
this.str = str;
}
public String getStr() {
return this.str;
}
private String str;
}
最后是客户端的示意代码,这里按照内容的字符顺序,依次调用各个字符翻译类来翻译:
import java.util.List;
import java.util.ArrayList;
public class Client {
public static void main(String[] argv) {
Context context = new Context("我 爱 你");
List list = new ArrayList();
list.add(new WoInterpreter());
list.add(new FuhaoInterpreter());
list.add(new AiInterpreter());
list.add(new FuhaoInterpreter());
list.add(new NiInterpreter());
for (int i = 0; i < list.size(); i++) {
Interpreter interpreter = (Interpreter)list.get(i);
interpreter.parse(context);
}
}
}