解释器模式

该代码示例展示了如何用Python实现解释器模式,用于解析和执行基于简单字符串的条件表达式。类如TerminalExpression、OrExpression和AndExpression分别代表词法元素、逻辑或和逻辑与操作。InterpreterPatternDemo类则展示了如何组合这些表达式来判断名字是否为John或Married。
摘要由CSDN通过智能技术生成
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

解释器模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值