The Interpreter Pattern states that it is necessary to establish a formal structure that represents the grammar of a specific language. Additionally, an interpreter is required to utilize this structure in order to interpret sentences within the language.
The Interpreter pattern has a narrow scope of use. The discussion of the Interpreter pattern is limited to formal grammars, however it is not commonly employed in this domain due to the availability of more effective solutions.
This approach can be utilized for parsing phrases that are defined in straightforward grammars and occasionally in basic rule engines.
SQL Parsing employs the interpreter design pattern.
The Interpreter pattern is used
- when the syntax of a language is relatively simple.
- when prioritizing efficiency is not a concern.
Source code Expression.java
package com.t4b.test.java.dp.bp.ip;
interface Expression {
public boolean evaluate(String context);
}
Source code AndExpression.java
package com.t4b.test.java.dp.bp.ip;
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 evaluate(String context) {
return expr1.evaluate(context) && expr2.evaluate(context);
}
}
Source code IsInExpression.java
package com.t4b.test.java.dp.bp.ip;
class IsInExpression implements Expression {
private String data;
public IsInExpression(String data) {
this.data = data;
}
@Override
public boolean evaluate(String context) {
if (context.contains(data)) {
return true;
}
return false;
}
}
Source code OrExpression.java
package com.t4b.test.java.dp.bp.ip;
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 evaluate(String context) {
return expr1.evaluate(context) || expr2.evaluate(context);
}
}
Source code TestMain.java
package com.t4b.test.java.dp.bp.ip;
public class TestMain {
public static void main(String[] args) {
Expression select = new IsInExpression("Select");
Expression from = new IsInExpression("From");
Expression isSelectFrom = new AndExpression(select, from);
Expression insert = new IsInExpression("Insert");
Expression update = new IsInExpression("Update");
Expression isInsertOrUpdate = new OrExpression(insert, update);
System.out.println(isSelectFrom.evaluate("Select"));
System.out.println(isInsertOrUpdate.evaluate("Insert"));
System.out.println(isSelectFrom.evaluate("Select From"));
System.out.println(isInsertOrUpdate.evaluate("Update"));
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.