提供了评估语言的语法或表达式的方式,它属于行为模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。这种模式常被用在 babel、sass、less 解析、符号处理引擎等
// 终端解释器
class TerminalExpression {
constructor(data) {
this.data = data
}
interpret(context) {
if(context.includes(context)){
return true
}
return false
}
}
// 或 的组合表达式
class OrExpression {
constructor(expr1, expr2) {
this.expr1 = expr1
this.expr2 = expr2
}
interpret(context) {
return this.expr1.interpret(context) || this.expr2.interpret(context)
}
}
// 与 的组合表达式
class AndExpression {
constructor(expr1, expr2) {
this.expr1 = expr1
this.expr2 = expr2
}
interpret(context) {
return this.expr1.interpret(context) && this.expr2.interpret(context)
}
}
const robert = new TerminalExpression('Robert')
const john = new TerminalExpression('John')
const isMale = new OrExpression(robert, john)
const julie = new TerminalExpression('Julie')
const married = new TerminalExpression('Married ')
const isMarriedWoman = new AndExpression(julie, married)
console.log(`John is male ? ${isMale.interpret('john')}`) // John is male ? true
console.log(`Julie is a married women ? ${isMarriedWoman.interpret('Married Julie')}`) // Julie is a married women ? true