设计模式-行为型模式,解释器模式(12)

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

对每个应用来说,至少有以下两种不同的用户分类。
? 基本用户:这类用户只希望能够凭直觉使用应用。他们不喜欢花太多时间配置或学习应
用的内部。对他们来说,基本的用法就足够了。
? 高级用户:这些用户,实际上通常是少数,不介意花费额外的时间学习如何使用应用的
高级特性。如果知道学会之后能得到以下好处,他们甚至会去学习一种配置(或脚本)
语言。
? 能够更好地控制一个应用
? 以更好的方式表达想法
? 提高生产力
解释器(Interpreter)模式仅能引起应用的高级用户的兴趣。这是因为解释器模式背后的主
要思想是让非初级用户和领域专家使用一门简单的语言来表达想法。然而,什么是一种简单的语
言?对于我们的需求来说,一种简单的语言就是没编程语言那么复杂的语言

# coding: utf-8

from pyparsing import Word, OneOrMore, Optional, Group, Suppress, alphanums

class Gate:

    def __init__(self):
        self.is_open = False

    def __str__(self):
        return ‘open‘ if self.is_open else ‘closed‘

    def open(self):
        print(‘opening the gate‘)
        self.is_open = True

    def close(self):
        print(‘closing the gate‘)
        self.is_open = False

class Garage:

    def __init__(self):
        self.is_open = False

    def __str__(self):
        return ‘open‘ if self.is_open else ‘closed‘

    def open(self):
        print(‘opening the garage‘)
        self.is_open = True

    def close(self):
        print(‘closing the garage‘)
        self.is_open = False

class Aircondition:

    def __init__(self):
        self.is_on = False

    def __str__(self):
        return ‘on‘ if self.is_on else ‘off‘

    def turn_on(self):
        print(‘turning on the aircondition‘)
        self.is_on = True

    def turn_off(self):
        print(‘turning off the aircondition‘)
        self.is_on = False

class Heating:

    def __init__(self):
        self.is_on = False

    def __str__(self):
        return ‘on‘ if self.is_on else ‘off‘

    def turn_on(self):
        print(‘turning on the heating‘)
        self.is_on = True

    def turn_off(self):
        print(‘turning off the heating‘)
        self.is_on = False

class Boiler:

    def __init__(self):
        self.temperature = 83  # in celsius

    def __str__(self):
        return ‘boiler temperature: {}‘.format(self.temperature)

    def increase_temperature(self, amount):
        print("increasing the boiler‘s temperature by {} degrees".format(amount))
        self.temperature += amount

    def decrease_temperature(self, amount):
        print("decreasing the boiler‘s temperature by {} degrees".format(amount))
        self.temperature -= amount

class Fridge:

    def __init__(self):
        self.temperature = 2  # 单位为摄氏度

    def __str__(self):
        return ‘fridge temperature: {}‘.format(self.temperature)

    def increase_temperature(self, amount):
        print("increasing the fridge‘s temperature by {} degrees".format(amount))
        self.temperature += amount

    def decrease_temperature(self, amount):
        print("decreasing the fridge‘s temperature by {} degrees".format(amount))
        self.temperature -= amount

def main():
    word = Word(alphanums)
    command = Group(OneOrMore(word))
    token = Suppress("->")
    device = Group(OneOrMore(word))
    argument = Group(OneOrMore(word))
    event = command + token + device + Optional(token + argument)

    gate = Gate()
    garage = Garage()
    airco = Aircondition()
    heating = Heating()
    boiler = Boiler()
    fridge = Fridge()

    tests = (‘open -> gate‘,
             ‘close -> garage‘,
             ‘turn on -> aircondition‘,
             ‘turn off -> heating‘,
             ‘increase -> boiler temperature -> 5 degrees‘,
             ‘decrease -> fridge temperature -> 2 degrees‘)
    open_actions = {‘gate‘: gate.open,
                    ‘garage‘: garage.open,
                    ‘aircondition‘: airco.turn_on,
                    ‘heating‘: heating.turn_on,
                    ‘boiler temperature‘: boiler.increase_temperature,
                    ‘fridge temperature‘: fridge.increase_temperature}
    close_actions = {‘gate‘: gate.close,
                     ‘garage‘: garage.close,
                     ‘aircondition‘: airco.turn_off,
                     ‘heating‘: heating.turn_off,
                     ‘boiler temperature‘: boiler.decrease_temperature,
                     ‘fridge temperature‘: fridge.decrease_temperature}

    for t in tests:
        if len(event.parseString(t)) == 2:  # 没有参数
            cmd, dev = event.parseString(t)
            cmd_str, dev_str = ‘ ‘.join(cmd), ‘ ‘.join(dev)
            if ‘open‘ in cmd_str or ‘turn on‘ in cmd_str:
                open_actions[dev_str]()
            elif ‘close‘ in cmd_str or ‘turn off‘ in cmd_str:
                close_actions[dev_str]()
        elif len(event.parseString(t)) == 3:  # 有参数
            cmd, dev, arg = event.parseString(t)
            cmd_str, dev_str, arg_str = ‘ ‘.join(cmd), ‘ ‘.join(dev), ‘ ‘.join(arg)
            num_arg = 0
            try:
                num_arg = int(arg_str.split()[0])  # 抽取数值部分
            except ValueError as err:
                print("expected number but got: ‘{}‘".format(arg_str[0]))
            if ‘increase‘ in cmd_str and num_arg > 0:
                open_actions[dev_str](num_arg)
            elif ‘decrease‘ in cmd_str and num_arg > 0:
                close_actions[dev_str](num_arg)

if __name__ == ‘__main__‘:
    main()

原文地址:https://www.cnblogs.com/ydf0509/p/8526064.html

时间: 2024-07-30 09:53:48

设计模式-行为型模式,解释器模式(12)的相关文章

设计模式(行为型)之解释器模式(Interpreter Pattern)

PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbober] 阅读前一篇<设计模式(行为型)之访问者模式(Visitor Pattern)>http://blog.csdn.net/yanbober/article/details/45536787 概述 解释器模式是类的行为模式.给定一个语言之后,解释器模式可以定义出其文法的一种表示,并同时提供一个

[设计模式-行为型]责任链模式(Chain of Responsibility)

概括 名称 Chain of Responsibility 结构 动机 使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系.将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止. 适用性 有多个的对象可以处理一个请求,哪个对象处理该请求运行时刻自动确定. 你想在不明确指定接收者的情况下,向多个对象中的一个提交一个请求. 可处理一个请求的对象集合应被动态指定. 解析 形象比喻: 晚上去上英语课, 为了好开溜坐到了最后一排, 哇, 前面坐了好几个漂亮的MM 哎

设计模式(行为型)之策略模式(Strategy Pattern)

PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbober] 阅读前一篇<设计模式(行为型)之迭代器模式(Iterator Pattern)>http://blog.csdn.net/yanbober/article/details/45497881 概述 使用策略模式可以定义一些独立的类来封装不同的算法,每一个类封装一种具体的算法,在这里,每一个封

设计模式(行为型)之迭代器模式(Iterator Pattern)

PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbober] 阅读前一篇<设计模式(行为型)之观察者模式(Observer Pattern)>http://blog.csdn.net/yanbober/article/details/45484749 概述 在软件构建过程中,集合对象内部结构常常变化各异.但对于这些集合对象,我们希望在不暴露其内部结构

设计模式(行为型)之备忘录模式(Memento Pattern)

PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbober] 阅读前一篇<设计模式(行为型)之中介者模式(Mediator Pattern)>http://blog.csdn.net/yanbober/article/details/45533335 概述 备忘录模式提供了一种状态恢复的实现机制,使得用户可以方便地回到一个特定的历史步骤,当新的状态无

设计模式(行为型)之命令模式(Command Pattern)

PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbober] 阅读前一篇<设计模式(行为型)之策略模式(Strategy Pattern)>http://blog.csdn.net/yanbober/article/details/45498567 概述 在软件开发中,我们经常需要向某些对象发送请求(调用其中的某个或某些方法),但是并不知道请求的接收

设计模式(行为型)之模板方法模式(Template Method Pattern)

PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbober] 阅读前一篇<设计模式(行为型)之命令模式(Command Pattern)>http://blog.csdn.net/yanbober/article/details/45500113 概述 模板方法模式是一种基于继承的代码复用,它是一种类行为型模式:是结构最简单的行为型设计模式,在其结构

设计模式(行为型)之状态模式(State Pattern)

PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbober] 阅读前一篇<设计模式(行为型)之模板方法模式(Template Method Pattern)>http://blog.csdn.net/yanbober/article/details/45501715 概述 状态模式用于解决系统中复杂对象的状态转换以及不同状态下行为的封装问题.当系统中

行为型模式--解释器模式

解释器模式 解释器模式(Interpreter Pattern)提供了评估语言的语法或表达式的方式.这种模式实现了一个表达式接口,该接口解释一个特定的上下文.这种模式被用在SQL解析.符号处理引擎等. 介绍 意图:给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子. 主要解决:对于一些固定文法构建一个解释句子的解释器. 何时使用:如果一种特定类型的问题发生的频率足够高,那么可能就值得将该问题的各个实例表述为一个简单语言中的句子.这样就可以构建一个解释器,该解

设计模式15:Interpreter 解释器模式(行为型模式)

Interpreter 解释器模式(行为型模式) 动机(Motivation) 在软件构建过程中,如果某一特定领域的问题比较复杂,类似的模式不断重复出现,如果使用普通的编程方式来实现将面临非常频繁的变化. 在这种情况下,将特定领域的问题表达为某种语法规则下的句子,然后构建一个解释器来解释这样的句子,从而达到解决问题的目的. 意图(Intent) 给定一个语言,定义它的文法的一种表示,并定义一种解释器,这个解释器用来解释语言中的句子.——<设计模式>GoF 中文数字转换为阿拉伯数字 public