解释器模式(Interpreter)定义:给分析对象定义一个语言,并定义该语言的文法表示,再设计一个解析器来解释语言中的句子。也就是说,用编译语言的方式来分析应用中的实例。这种模式实现了文法表达式处理的接口,该接口解释一个特定的上下文。

解释器模式的优点有:

1、扩展性好。由于在解释器模式中使用类来表示语言的文法规则,因此可以通过继承等机制来改变或扩展文法。

2、容易实现。在语法树中的每个表达式节点类都是相似的,所以实现其文法较为容易。

 

环境类:

 1 public class Context {
 2     private String[] citys = { "韶关", "广州" };
 3     private String[] persons = { "老人", "妇女", "儿童" };
 4     private AbstractExpression cityPerson;
 5 
 6     public Context() {
 7         AbstractExpression city = new TerminalExpression(citys);
 8         AbstractExpression person = new TerminalExpression(persons);
 9         cityPerson = new AndExpression(city, person);
10     }
11 
12     public void freeRide(String info) {
13         Boolean ok = cityPerson.interpret(info);
14         if (ok)
15             System.out.println("您是" + info + ",您本次乘车免费!");
16         else
17             System.out.println(info + ",您不是免费人员,本次乘车扣费2元!");
18     }
19 }

 

表达式类:

 1 public interface AbstractExpression {
 2     public Boolean interpret(String info); // 解释方法
 3 }
 4 
 5 public class TerminalExpression implements AbstractExpression {
 6     private Set<String> set = new HashSet<String>();
 7 
 8     public TerminalExpression(String[] data) {
 9         for (int i = 0; i < data.length; i++)
10             set.add(data[i]);
11     }
12 
13     public Boolean interpret(String info) {
14         if (set.contains(info)) {
15             return true;
16         }
17         return false;
18     }
19 }
20 
21 public class AndExpression implements AbstractExpression {
22     private AbstractExpression city = null;
23     private AbstractExpression person = null;
24 
25     public AndExpression(AbstractExpression city, AbstractExpression person) {
26         this.city = city;
27         this.person = person;
28     }
29 
30     public Boolean interpret(String info) {
31         String s[] = info.split("的");
32         return city.interpret(s[0]) && person.interpret(s[1]);
33     }
34 }

 

调用方式:

 1 //解释器
 2 public class Client {
 3     public static void main(String[] args) {
 4         Context bus = new Context();
 5         bus.freeRide("韶关的老人");
 6         bus.freeRide("韶关的年轻人");
 7         bus.freeRide("广州的妇女");
 8         bus.freeRide("广州的儿童");
 9         bus.freeRide("山东的儿童");
10     }
11 }

执行结果:

 

posted on 2019-12-28 11:20  Sempron2800+  阅读(139)  评论(0编辑  收藏  举报