提供了评估语言和表达式的方式

使用场景

  1. 解决重复类型的问题,
  2. 通过构建语法树解释语音

Demo

  1. """
  2. 解释器模式
  3. """
  4. class Expression:
  5. def interpret(self, context):
  6. raise NotImplementedError()
  7. class TerminalExpression(Expression):
  8. def __init__(self, data: str):
  9. self.data = data
  10. def interpret(self, context: str):
  11. if context.find(self.data) > -1:
  12. return True
  13. return False
  14. class OrExpression(Expression):
  15. def __init__(self, expr1: Expression, expr2: Expression):
  16. self.expr1 = expr1
  17. self.expr2 = expr2
  18. def interpret(self, context):
  19. return self.expr1.interpret(context) or self.expr2.interpret(context)
  20. class AndExpression(Expression):
  21. def __init__(self, expr1: Expression, expr2: Expression):
  22. self.expr1 = expr1
  23. self.expr2 = expr2
  24. def interpret(self, context):
  25. return self.expr1.interpret(context) and self.expr2.interpret(context)
  26. def get_male_expression():
  27. r = TerminalExpression('r')
  28. m = TerminalExpression('m')
  29. return OrExpression(r, m)
  30. def get_married_woman_expression():
  31. j = TerminalExpression('j')
  32. m = TerminalExpression('m')
  33. return AndExpression(j, m)
  34. if __name__ == '__main__':
  35. is_male = get_male_expression()
  36. print("r is male:", is_male.interpret('r'))
  37. is_married_expression = get_married_woman_expression()
  38. print(f"ju is a married women:", is_married_expression.interpret('j m'))