解释器模式的类图如下:
定义了上下文对象,在对象中有两个数,我们要对这两个数进行对应的运算。我们在接口中定义了解释器,其中有一个解释的方法。在加法中我们实际的解释加的具体操作是什么。
[java]
- public interface Expression {
- public int interpret(Context context);
- }
[java]
- public class Plus implements Expression {
- @Override
- public int interpret(Context context) {
- return context.getNum1()+context.getNum2();
- }
- }
[java]
- public class Minus implements Expression {
- @Override
- public int interpret(Context context) {
- return context.getNum1()-context.getNum2();
- }
- }
[java]
- public class Context {
- private int num1;
- private int num2;
- public Context(int num1, int num2) {
- this.num1 = num1;
- this.num2 = num2;
- }
- public int getNum1() {
- return num1;
- }
- public void setNum1(int num1) {
- this.num1 = num1;
- }
- public int getNum2() {
- return num2;
- }
- public void setNum2(int num2) {
- this.num2 = num2;
- }
- }
- public class Test {
- public static void main(String[] args) {
- // 计算9+2-8的值
- int result = new Minus().interpret((new Context(new Plus()
- .interpret(new Context(9, 2)), 8)));
- System.out.println(result);
- }
- }