Java学习-设计模式-解释器模式
概述:
解释器模式提供了评估语言的语法或表达式的方式,它属于行为型模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。这种模式被用在 SQL 解析、符号处理引擎等。
优点: 1、可扩展性比较好,灵活。 2、增加了新的解释表达式的方式。 3、易于实现简单文法。
缺点: 1、可利用场景比较少。 2、对于复杂的文法比较难维护。 3、解释器模式会引起类膨胀。 4、解释器模式采用递归调用方法。
使用场景: 1、可以将一个需要解释执行的语言中的句子表示为一个抽象语法树。 2、一些重复出现的问题可以用一种简单的语言来进行表达。 3、一个简单语法需要解释的场景。
**何时使用:**如果一种特定类型的问题发生的频率足够高,那么可能就值得将该问题的各个实例表述为一个简单语言中的句子。这样就可以构建一个解释器,该解释器通过解释这些句子来解决该问题。
理解:
这个想了很久(也不是很久,就是每天下班回来看一下,看了两三晚),但是呢不知道自己的理解正不正确。
就是对你所输入的语言进行解释,比如说你输入一个计算公式简单的加减乘除,这个你输入到电脑的是字符串,程序运行时将你输入的字符串解析出来,变成数学公式计算出来。
还比如说,一个判断类容,你输入篮子里有苹果或者香蕉吗?程序对其进行解析,并返回对应的结果给你。
以篮子中的水果举例
1. 首先创建一个水果接口 A,包含一个判定方法
2. 再创建一个实现类 A1 实现这个接口,包含一个水果名的属性并在构造方法中初始化它,然后重写判定方法,判断输入语句有没有涉及到这个水果
3.再创建一个and类 B1 也实现水果接口,包含两个上面实现类的属性,并在构造方法中初始化好,重写判定方法,判断两种水果是否同时存在
4. 还可以再创建一个OR类,按照and类编写,只是判断是否存在其中一个
5. 初始化好这两个水果类,使用or方法判断篮子里是否存在两种水果
package Practices.Mode.Interpreter_Pattern;
// 1. 先定义一个水果的接口
public interface Fruit {
public boolean exist_Fruit(String question);
}
package Practices.Mode.Interpreter_Pattern;
// 2. 创建实现类来实现水果接口,变成具体的水果
public class RealFruit implements Fruit {
public String fruit_name;
public RealFruit(String fruit_name) {
this.fruit_name = fruit_name;
}
public boolean exist_Fruit(String question) {
if(question.contains(fruit_name)){
return true;
}
return false;
}
}
package Practices.Mode.Interpreter_Pattern;
// 3. 比较是否同时存在
public class And_Copmare {
private Fruit fruit1;
private Fruit fruit2;
public And_Copmare(Fruit fruit1, Fruit fruit2) {
this.fruit1 = fruit1;
this.fruit2 = fruit2;
}
public void Compare(String sentence){
if(fruit1.exist_Fruit(sentence) && fruit2.exist_Fruit(sentence)){
System.out.println("同时存在");
}else{
System.out.println("不同时存在");
}
}
}
package Practices.Mode.Interpreter_Pattern;
// 4. 比较是否存在其中一种
public class Or_Compare {
private Fruit fruit1;
private Fruit fruit2;
public Or_Compare(Fruit fruit1, Fruit fruit2) {
this.fruit1 = fruit1;
this.fruit2 = fruit2;
}
public void Compare(String sentence){
if(fruit1.exist_Fruit(sentence) || fruit2.exist_Fruit(sentence)){
System.out.println("至少存在其中一种");
}else{
System.out.println("不存在");
}
}
}
package Practices.Mode.Interpreter_Pattern;
// 5. 测试
public class Test_main {
public static void main(String[] args) {
Fruit apple = new RealFruit("苹果");
Fruit banana = new RealFruit("香蕉");
And_Copmare andCopmare = new And_Copmare(apple, banana);
Or_Compare orCompare = new Or_Compare(apple, banana);
String sentence = new String(new StringBuffer("篮子里有梨或者苹果吗"));
if(sentence.contains("和")){
andCopmare.Compare(sentence);
}
if (sentence.contains("或")){
orCompare.Compare(sentence);
}
}
}