解释器模式,包含如下几类角色:
- context: 全局上下文,将作为参数传入解释器
- Interpret:解释器的抽象,本例中是Expression
- ConcreteInterpret:某个具体的解释器,本例中是OneExpression
代码如下:
- Context
public class Context { private String value; public Context(){ this.value = "Init"; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
- Expression
public interface Expression { public void interpret(Context context); }
- OneExpression
public class OneExpression implements Expression { @Override public void interpret(Context context) { System.out.println("OneExpression interpret " + context.getValue()); } }
- APP 测试类
public class App { public static void main(String[] args) { Context context = new Context(); OneExpression expression = new OneExpression(); expression.interpret(context); } }
时间: 2024-10-13 09:27:43