当前位置:网站首页>Interpreter mode -- formulas for dating
Interpreter mode -- formulas for dating
2022-06-24 20:35:00 【zhanyd】
List of articles
Introduction
Xiaomei has been urged by her family to have a blind date recently , Family relatives introduced several boys , Xiaomei is not satisfied . Xiaomei has high requirements : At least have a room ? The annual income shall not be less than 20 Ten thousand bar ? The lowest height is also required 175cm Well ? Don't be too old , No more than 30 Year old. ? You should start with a bachelor's degree ?
what ? You think I'm asking too much ? To say , If your family is rich , Other conditions can also be relaxed !
Xiaomei is really a procedural yuan , She made a formula for her blind date conditions :
house >= 1 && Annual income >= 20 && height >= 175 && Age < 30 && Education >= 4 || property >= 1000
Xiaomei gives this formula to the matchmaker , And asked the boys who must meet this formula to arrange blind dates . The matchmaker was stunned at the sight , Why is there a formula , The girl , I'm just a matchmaker , I haven't studied mathematics , Don't you embarrass me ?
Xiaomei said : Don't worry , The formula is applied to ensure the correct result , Listen to me carefully , This has to start with the interpreter mode …
woman matchmaker : I don't understand that …
Xiaomei : No , You understand …
Interpreter mode
Interpreter mode : Define its syntax for a language ( Or grammar ) Express , And define an interpreter to handle this syntax .(Interpreter pattern is used to defines a grammatical representation for a language and provides an interpreter to deal with this grammar.)
In plain English : We can define some symbols by ourselves , Then we set rules for these symbols , The power of interpretation lies in our own hands .
For example, an expression ”1#2!3“, We can define ”#“ Express ”+“ Number ,”!” Express “-” Number , How to explain our own the final say .
The class diagram of the Interpreter pattern is as follows :
I use the expression a+b-c To apply :
- AbstractExpression: abstract interpreter , The specific interpretation task is completed by each implementation class , The specific interpreter is composed of TerminalExpression and NonterminalExpression complete .
- TerminalExpression: Terminator expression , It's corresponding to “a”,“b”,“c”.
- NonterminalExpression: Nonterminal expression , It's corresponding to “+”,“-” Symbol .
- Context: Some global information outside the interpreter , In the following example, it is in the client Map.
Expressions for blind dates , The structure shown in the figure below is adopted :
after one's words , Xiaomei throws a piece of code :
So let's assume that “ >= ”,“<” Symbols have priority over “&&” and “||” high ,“&&” The priority ratio “||” high .
Expression interface class :
/** * Expression interface */
public interface Expression {
/** * Explain expression * @param states * @return */
boolean interpret(Map<String, Integer> states);
}
Greater than or equal to expression class :
/** * Greater than or equal to expression */
public class GreaterOrEqualExpression implements Expression {
private String key;
private int value;
public GreaterOrEqualExpression(String key, int value) {
this.key = key;
this.value = value;
}
public GreaterOrEqualExpression(String strExpression) {
String[] elements = strExpression.trim().split("\\s+");
if(elements.length != 3 || !elements[1].trim().equals(">=")) {
throw new RuntimeException("Expression is invalid: " + strExpression);
}
this.key = elements[0].trim();
this.value = Integer.parseInt(elements[2].trim());
}
/** * Explain the expression greater than or equal to * @param states * @return */
@Override
public boolean interpret(Map<String, Integer> states) {
if(!states.containsKey(key)) {
return false;
}
int stateValue = states.get(key);
return stateValue >= value;
}
}
Less than expression class :
/** * Less than expression */
public class LessExpression implements Expression {
private String key;
private int value;
public LessExpression(String key, int value) {
this.key = key;
this.value = value;
}
public LessExpression(String strExpression) {
String[] elements = strExpression.trim().split("\\s+");
if(elements.length != 3 || !elements[1].trim().equals("<")) {
throw new RuntimeException("Expression is invalid: " + strExpression);
}
this.key = elements[0].trim();
this.value = Integer.parseInt(elements[2].trim());
}
/** * Explain less than expression * @param states * @return */
@Override
public boolean interpret(Map<String, Integer> states) {
if(!states.containsKey(key)) {
return false;
}
int stateValue = states.get(key);
return stateValue < value;
}
}
And expression classes :
/** * And the expression */
public class AndExpression implements Expression {
private List<Expression> expressions = new ArrayList<>();
public AndExpression(List<Expression> expressions) {
this.expressions = expressions;
}
public AndExpression(String strAndExpression) {
String[] strExpressions = strAndExpression.split("&&");
for(String strExpr : strExpressions) {
if(strExpr.contains(">=")) {
expressions.add(new GreaterOrEqualExpression(strExpr));
} else if(strExpr.contains("<")) {
expressions.add(new LessExpression(strExpr));
} else {
throw new RuntimeException("Expression is invalid: " + strAndExpression);
}
}
}
/** * Explanation and expression * * @param states * @return */
@Override
public boolean interpret(Map<String, Integer> states) {
for(Expression expr : expressions) {
if(!expr.interpret(states)) {
return false;
}
}
return true;
}
}
Or expression class :
/** * Or expressions */
public class OrExpression implements Expression {
private List<Expression> expressions = new ArrayList<>();
public OrExpression(List<Expression> expressions) {
this.expressions = expressions;
}
public OrExpression(String strOrExpression) {
String[] andExpressions = strOrExpression.split("\\|\\|");
for(String andExpr : andExpressions) {
// && Expressions take precedence over || Expression high , Calculation || The expression must be evaluated before && expression
// Reuse here && expression
expressions.add(new AndExpression(andExpr));
}
}
/** * An explanation or expression * * @param states * @return */
@Override
public boolean interpret(Map<String, Integer> states) {
for(Expression expr : expressions) {
if(expr.interpret(states)) {
return true;
}
}
return false;
}
}
Affinity expression parsing class :
/** * Analysis of dating expression */
public class BlindDateRuleInterpreter {
private Expression expression;
/** * Start with the or expression * @param ruleExpression */
public BlindDateRuleInterpreter(String ruleExpression) {
this.expression = new OrExpression(ruleExpression);
}
public boolean interpret(Map<String, Integer> states) {
return expression.interpret(states);
}
}
Client test class :
/** * Client test class */
public class ClientTest {
public static void main(String[] args) {
// In order to be closer to life , there key Just use Chinese
String rule = " house >= 1 && Annual income >= 20 && height >= 175 && Age < 30 && Education >= 4 || property >= 1000";
BlindDateRuleInterpreter interpreter = new BlindDateRuleInterpreter(rule);
Map<String, Integer> states = new HashMap<>();
states.put(" house ", 1);
states.put(" Annual income ", 20);
states.put(" height ", 176);
states.put(" Age ", 28);
states.put(" Education ", 4);
states.put(" property ", 100);
// Judge the dating condition according to the expression
boolean qualified = interpreter.interpret(states);
if(qualified) {
System.out.println(" brother , Congratulations, you are qualified !");
} else {
System.out.println(" brother , We need to continue to work on !");
}
}
}
Output :
brother , Congratulations, you are qualified !
summary
The Interpreter pattern describes how to define a grammar for a simple language , How to express a sentence in the language , And how to explain these sentences .
The core of the interpreter is to split the parsing work into various sub classes , In order to avoid large and complete parsing classes . The general way is , Split the grammar rules into small independent units , Then analyze each unit , Finally, it is merged into the analysis of the whole grammar rules .
advantage
- Interpreter is a simple parsing tool , Its most significant advantage is scalability , To modify the syntax rules, just modify the corresponding non terminal expression , If extended grammar , You just need to add a non terminator class .
shortcoming
- Interpreter mode causes class inflation , Each syntax produces a nonterminal expression , When the grammar rules are complex , It is possible to produce a large number of class files , It brings a lot of trouble for maintenance .
- The Interpreter pattern may use a lot of loops and recursion , Efficiency is a problem that cannot be ignored , Especially for parsing complex 、 Lengthy grammar , Low efficiency .
Postscript
Xiaomei : Hello, aunt , Three months have passed , Why didn't you introduce me to any of the boys ?
woman matchmaker : Oh dear , There is no suitable one ! I put the conditions of a dozen boys into the formula, and only one of them met the conditions , Then the other party thinks your conditions are not good enough . Don't worry. , I'll look for you again .
Xiaomei : forehead … Then I don't want the formula , As long as you have a good character 、 Values are just fine , Good character is the most important , Let's talk about the others when we meet .
woman matchmaker : Good. , That's easy to do , I'll keep an eye on you .
边栏推荐
- 伯克利、MIT、剑桥、DeepMind等业内大佬线上讲座:迈向安全可靠可控的AI
- Leetcode (455) - distribute cookies
- [multi thread performance tuning] multi thread lock optimization (Part 1): optimization method of synchronized synchronization lock
- Berkeley, MIT, Cambridge, deepmind and other industry leaders' online lectures: towards safe, reliable and controllable AI
- Ribbon源码分析之@LoadBalanced与LoadBalancerClient
- CVPR 2022缅怀孙剑!同济、阿里获最佳学生论文奖,何恺明入围
- The latest simulated question bank and answers of the eight members (Electrical constructors) of Sichuan architecture in 2022
- lol手游之任务进度条精准计算
- CVPR 2022 remembers Sun Jian! Tongji and Ali won the best student thesis award, and hekaiming was shortlisted
- Sequential stack traversal binary tree
猜你喜欢

Cooking business experience of young people: bloggers are busy selling classes and bringing goods, and the organization earns millions a month

微信小程序自定义tabBar

物联网?快来看 Arduino 上云啦

Mapstacks: data normalization and layered color layer loading

Set up your own website (14)

云计算发展的 4 个阶段,终于有人讲明白了

Freshman girls' nonsense programming is popular! Those who understand programming are tied with Q after reading

Stackoverflow 年度报告 2022:开发者最喜爱的数据库是什么?

海泰前沿技术|隐私计算技术在医疗数据保护中的应用
![[performance tuning basics] performance tuning strategy](/img/83/be41a6a0c5c186d3fb3a120043c53f.jpg)
[performance tuning basics] performance tuning strategy
随机推荐
Bytebase加入阿里云PolarDB开源数据库社区
Map跟object 的区别
Compressed list of redis data structures
Apple doesn't need money, but it has no confidence in its content
微信小程序中使用vant组件
It is said that Tencent officially announced the establishment of "XR" department to bet on yuanuniverse; Former CEO of Google: the United States is about to lose the chip competition. We should let T
Bytebase joins Alibaba cloud polardb open source database community
unity实战之lol技能释放范围
伯克利、MIT、劍橋、DeepMind等業內大佬線上講座:邁向安全可靠可控的AI
What is showcase? What should showcase pay attention to?
redis数据结构之压缩列表
物联网?快来看 Arduino 上云啦
顺序栈1.0版本
图的基本概念以及相关定义
顺序栈遍历二叉树
微信小程序自定义tabBar
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
VMware virtual machine setting static IP
[cann document express issue 04] unveiling the development of shengteng cann operator
Introduction: continuously update the self-study version of the learning manual for junior test development engineers