标签:
一般主要应用在OOP开发中的编译器的开发中,所以适用面比较窄。
public interface Expression { public int interpret(Context context); }
public class Plus implements Expression{ @Override public int interpret(Context context) { // TODO Auto-generated method stub return context.getNum1()+context.getNum2(); } }
public class Minus implements Expression{ @Override public int interpret(Context context) { // TODO Auto-generated method stub return context.getNum1()-context.getNum2(); } }
public class Context { private int num1, num2; public int getNum1() { return num1; } public int getNum2() { return num2; } public void setNum1(int num) { this.num1 = num; } public void setNum2(int num) { this.num2 = num; } public Context(int num1, int num2) { this.num1 = num1; this.num2 = num2; } }
测试类:
/** * 解析器模式 * @author Administrator * */ public class Test { public static void main(String[] args) { // TODO Auto-generated method stub // 计算9+8-7 int result = new Minus().interpret((new Context(new Plus() .interpret(new Context(9, 8)), 7))); System.out.println(result); } }
最后输出正确的结果:10
基本就这样,解释器模式用来做各种各样的解释器,如正则表达式等的解释器等等!
标签:
原文地址:http://my.oschina.net/carbenson/blog/505750