解释器模式(Interpreter Pattern)
|
1 2 3 |
定义:提供了评估语言的语法或表达式的方式。 目的:对于一些固定文法构建一个解释句子的解释器。 场景:编译器、运算表达式计算。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
// 基础表达式:判断是否包含关键词 class Keyword { constructor(word) { this.word = word } interpret(context) { return context.includes(this.word) } } // 或表达式:满足任意一个条件 class Or { constructor(left, right) { this.left = left this.right = right } interpret(context) { return this.left.interpret(context) || this.right.interpret(context) } } // 与表达式:必须同时满足两个条件 class And { constructor(left, right) { this.left = left this.right = right } interpret(context) { return this.left.interpret(context) && this.right.interpret(context) } } // 构建规则:(John OR Robert) AND Married const rule = new And( new Or( new Keyword('John'), new Keyword('Robert') ), new Keyword('Married') ) // 解释输入,得到结果 console.log(rule.interpret('John Married')) // true console.log(rule.interpret('Robert Married')) // true console.log(rule.interpret('John')) // false console.log(rule.interpret('Julie Married')) // false |

