提供了评估语言的语法或表达式的方式,它属于行为模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。这种模式常被用在 babel、sass、less 解析、符号处理引擎等

  1. // 终端解释器
  2. class TerminalExpression {
  3. constructor(data) {
  4. this.data = data
  5. }
  6. interpret(context) {
  7. if(context.includes(context)){
  8. return true
  9. }
  10. return false
  11. }
  12. }
  13. // 或 的组合表达式
  14. class OrExpression {
  15. constructor(expr1, expr2) {
  16. this.expr1 = expr1
  17. this.expr2 = expr2
  18. }
  19. interpret(context) {
  20. return this.expr1.interpret(context) || this.expr2.interpret(context)
  21. }
  22. }
  23. // 与 的组合表达式
  24. class AndExpression {
  25. constructor(expr1, expr2) {
  26. this.expr1 = expr1
  27. this.expr2 = expr2
  28. }
  29. interpret(context) {
  30. return this.expr1.interpret(context) && this.expr2.interpret(context)
  31. }
  32. }
  33. const robert = new TerminalExpression('Robert')
  34. const john = new TerminalExpression('John')
  35. const isMale = new OrExpression(robert, john)
  36. const julie = new TerminalExpression('Julie')
  37. const married = new TerminalExpression('Married ')
  38. const isMarriedWoman = new AndExpression(julie, married)
  39. console.log(`John is male ? ${isMale.interpret('john')}`) // John is male ? true
  40. console.log(`Julie is a married women ? ${isMarriedWoman.interpret('Married Julie')}`) // Julie is a married women ? true

总结

优点

  • 可扩展性好
  • 灵活性高
  • 易于实现简单的文法

    缺点

  • 可利用的场景比较少

  • 对于复杂的文法的解析器维护困难
  • 解释器模式会引起类的膨胀
  • 解释器模式大量采用了递归和循环的调用方法、执行效率低下、性能消耗比较高