class TerminalExpression {
private data;
constructor(String data){
this.data = data;
}
interpret(context) {
if(context.contains(data)){
return true;
}
return false;
}
}
class OrExpression {
private expr1 = null;
private expr2 = null;
constructor(expr1, expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
}
interpret(context) {
return expr1.interpret(context) || expr2.interpret(context);
}
}
class AndExpression {
private expr1 = null;
private expr2 = null;
constructor(expr1, expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
}
interpret(String context) {
return expr1.interpret(context) && expr2.interpret(context);
}
}
class InterpreterPatternDemo {
//Rule: Robert and John are male
static getMaleExpression(){
const robert = new TerminalExpression("Robert");
const john = new TerminalExpression("John");
return new OrExpression(robert, john);
}
//Rule: Julie is a married women
static getMarriedWomanExpression(){
const julie = new TerminalExpression("Julie");
married = new TerminalExpression("Married");
const return new AndExpression(julie, married);
}
static run(args) {
const isMale = getMaleExpression();
const isMarriedWoman = getMarriedWomanExpression();
console.log("John is male? " + isMale.interpret("John"));
console.log("Julie is a married women? " + isMarriedWoman.interpret("Married Julie"));
}
}
InterpreterPatternDemo.run();
// John is male? true
// Julie is a married women? true