python 设计模式-解释器模式

mac2022-06-30  19

解释器模式主要用于语言语法的解析,我们平常开发中用的比较少。

示例代码如下:

#!/usr/bin/env python #coding: utf-8 from abc import ABCMeta, abstractmethod class Expression(metaclass=ABCMeta): @abstractmethod def interpret(self, context): pass class AtomExpression(Expression): def __init__(self, base): self._base = base def interpret(self, context): return context == self._base class OrExpression(Expression): def __init__(self, expr1, expr2): self._expr1 = expr1 self._expr2 = expr2 def interpret(self, context): return self._expr1.interpret(context) or self._expr2.interpret(context) class AndExpression(Expression): def __init__(self, expr1, expr2): self._expr1 = expr1 self._expr2 = expr2 def interpret(self, context): return self._expr1.interpret(context) and self._expr2.interpret(context) if __name__ == '__main__': a = AtomExpression('yes') b = AtomExpression('no') oe = OrExpression(a, b) ae = AndExpression(a, b) print('a: {}, b: {}, oe: {}, ae: {}'.format(a.interpret('yes'), b.interpret('no'), oe.interpret('yes'), ae.interpret('yes')))

输出:

a: True, b: True, oe: True, ae: False
最新回复(0)