class Expression:
@abstractmethod
def interpret(self, context: str) -> bool:
raise NotImplemented
class TerminalExpression(Expression):
data: str
def __init__(self, data: str):
self.data = data
def interpret(self, context: str) -> bool:
if context == self.data:
return True
return False
class OrExpression(Expression):
expr1: Expression = None
expr2: Expression = None
def __init__(self, expr1: Expression, expr2: Expression):
self.expr1 = expr1
self.expr2 = expr2
def interpret(self, context: str) -> bool:
return self.expr1.interpret(context) or self.expr2.interpret(context)
class AndExpression(Expression):
expr1: Expression = None
expr2: Expression = None
def __init__(self, expr1: Expression, expr2: Expression):
self.expr1 = expr1
self.expr2 = expr2
def interpret(self, context: str) -> bool:
return self.expr1.interpret(context) or self.expr2.interpret(context)
class InterpreterPatternDemo:
def __init__(self):
isMale: Expression = self.getMaleExpression()
isMarriedWoman: Expression = self.getMarriedWomanExpression()
print(f"John is male? {isMale.interpret('John')}")
print(f"Julie is a married women? {isMarriedWoman.interpret('Married Julie')}")
def getMaleExpression(self) -> Expression:
robert: Expression = TerminalExpression('Robert')
john: Expression = TerminalExpression('John')
return OrExpression(robert, john)
def getMarriedWomanExpression(self) -> Expression:
julie: Expression = TerminalExpression('Julie')
married: Expression = TerminalExpression('Married')
return OrExpression(julie, married)
if __name__ == '__main__':
InterpreterPatternDemo()
John is male? True
Julie is a married women? False