3. 行为型模式 (11) 解释器模式
程序员文章站
2022-07-12 23:37:42
...
3. 行为型模式 (11) 解释器模式
1. 解释器模式
解释器模式(Interpreter Pattern)实现了一个表达式接口,该接口解释一个特定的上下文。这种模式被用在 SQL 解析、符号处理引擎等。 优点: 1. 可扩展性比较好,灵活。 2. 增加了新的解释表达式的方式。 3. 易于实现简单文法。 缺点: 1. 可利用场景比较少。 2. 对于复杂的文法比较难维护。 3. 解释器模式会引起类膨胀。 4. 解释器模式采用递归调用方法。
1. 解释器模式
package com.andrew.pattern0311.interpreter.model01; public interface Expression { public boolean interpret(String context); }
package com.andrew.pattern0311.interpreter.model01; public class TerminalExpression implements Expression { private String data; public TerminalExpression(String data) { this.data = data; } @Override public boolean interpret(String context) { if (context.contains(data)) { return true; } return false; } } package com.andrew.pattern0311.interpreter.model01; public class OrExpression implements Expression { private Expression expr1 = null; private Expression expr2 = null; public OrExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) || expr2.interpret(context); } } package com.andrew.pattern0311.interpreter.model01; public class AndExpression implements Expression { private Expression expr1 = null; private Expression expr2 = null; public AndExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) && expr2.interpret(context); } }
package com.andrew.pattern0311.interpreter.model01; /** * 1. 解释器模式 * * @author andrew * @date 2018/11/08 */ public class Client { public static Expression getMaleExpression() { Expression robert = new TerminalExpression("Robert"); Expression john = new TerminalExpression("John"); return new OrExpression(robert, john); } public static Expression getMarriedWomanExpression() { Expression julie = new TerminalExpression("Julie"); Expression married = new TerminalExpression("Married"); return new AndExpression(julie, married); } public static void main(String[] args) { Expression isMale = getMaleExpression(); Expression isMarriedWoman = getMarriedWomanExpression(); System.out.println("John is male? " + isMale.interpret("John")); System.out.println("Julie is a married women? " + isMarriedWoman.interpret("Married Julie")); } } 运行结果: John is male? true Julie is a married women? true
上一篇: Java连接各种数据库的实例