간단한 언어의 문법을 정의하고 해석하는 패턴
언어가 주어지면 해당 표현을 사용하여 언어로 문장을 해석하는 인터프리터를 사용하여 문법 표현을 정의하는 방법
Expression.class
public interface Expression {
boolean interpreter(String con);
}
TerminalExpression.class
public class TerminalExpression implements Expression {
private String data;
public TerminalExpression(String data){
this.data = data;
}
@Override
public boolean interpreter(String context) {
if(context.contains(data)){
return true;
}
return false;
}
}
AndExpression.class
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 interpreter(String context) {
return expr1.interpreter(context) && expr2.interpreter(context);
}
}
OrExpression.class
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 interpreter(String context) {
return expr1.interpreter(context) || expr2.interpreter(context);
}
}
interpreter
구현체TerminalExpression
을 통해 데이터를 저장하고 각 구현체별로 정해진 기능을 사용Main.class
public class Main {
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.interpreter("John"));
System.out.println("Julie is a married women? " + isMarriedWoman.interpreter("Married Julie"));
}
}
실행결과
>>>John is male? true
>>>Julie is a married women? true
참조: