设计模式十三:解释器模式

什么是解释器模式

主要放向:让非初级用户和领域专家使用一门简单的语言来表达想法
一般是高级用户才会有所兴趣。

典型案例

音乐演奏者是现实中解释器模式的例子,
五线谱图形化地表达了声音的音调和持续时间(音乐语言)
音乐演奏者能根据五线谱的符合精确重现声音(语言解释器)

补充知识

领域特定语言(Domain Specific Language ,DSL):针对一个特定领域的有限表达能力的计算机语言。

巴科斯-诺尔形式定义简单语法:
event ::= command token receiver token arguments
command ::= word+
word ::= a collection of one or more alphanumeric characters
token ::= ->
receiver ::= word+
arguments ::= word+

实例代码

from pyparsing import Word,OneOrMore,Optional,Group,Suppress,alphanumsclass Gate:def __init__(self):self.is_open = Falsedef __str__(self):return 'open' if self.is_open else 'closed'def open(self):print('opening the gate')self.is_open = Truedef close(self):print('closing the gate')self.is_open = Falseclass Garage:def __init__(self):self.is_open = Falsedef __str__(self):return 'open' if self.is_open else 'closed'def open(self):print('opening the garage')self.is_open = Truedef close(self):print('closing the garage')self.is_open = Falseclass Aircondition:def __init__(self):self.is_on = Falsedef __str__(self):return 'on' if self.is_on else 'off'def turn_on(self):print('turning on  the aircondition')self.is_open = Truedef turn_off(self):print('turning off the aircondition')self.is_open = Falseclass Heating:def __init__(self):self.is_on = Falsedef __str__(self):return 'on' if self.is_on else 'off'def turn_on(self):print('turning on the heating')self.is_open = Truedef turn_off(self):print('turning off the heating')self.is_open = Falseclass Boiler:def __init__(self):self.temperature = 83 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 += amountdef decrease_temperature(self,amount):print('decreasing the boiler`s temperature by {} degrees'.format(amount))self.temperature -= amountclass Fridge:def __init__(self):self.temperature = 2def __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 += amountdef decrease_temperature(self,amount):print('decreasing the fridge`s temperature by {} degrees'.format(amount))self.temperature -= amountdef 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')# 解释语法1open_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}# 解释语法2close_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) # ['turn', 'on'] ['aircondition']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) # ['increase'] ['boiler', 'temperature'] ['5', 'degrees']cmd_str,dev_str,arg_str = ' '.join(cmd),' '.join(dev),' '.join(arg) # 需要以 空格 隔开num_arg = 0try: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()

Python设计模式:解释器模式相关推荐

  1. Python设计模式-解释器模式

    Python设计模式-解释器模式 代码基于3.5.2,代码如下; #coding:utf-8 #解释器模式class PlayContext():play_text = Noneclass Expre ...

  2. Python设计模式-建造者模式

    Python设计模式-建造者模式 代码基于3.5.2,代码如下; #coding:utf-8 #建造者模式 class Burger():name = ""price = 0.0d ...

  3. Python设计模式-状态模式

    Python设计模式-状态模式 代码基于3.5.2,代码如下; #coding:utf-8 #状态模式class state():def writeProgram(self,work):raise N ...

  4. Python设计模式-备忘录模式

    Python设计模式-备忘录模式 代码基于3.5.2,代码如下; #coding:utf-8 #备忘录模式 import randomclass gameCharacter():vitality = ...

  5. Python设计模式-命令模式

    Python设计模式-命令模式 代码基于3.5.2,代码如下; #coding:utf-8 #命令模式class barbecuer():def bakeButton(self):print(&quo ...

  6. Python设计模式-策略模式

    Python设计模式-策略模式 代码基于3.5.2,代码如下; #coding:utf-8 #策略模式class sendInterface():def send(self,value):raise ...

  7. Python设计模式-外观模式

    Python设计模式-外观模式 代码基于3.5.2,代码如下; #coding:utf-8 # 外观模式class AlarmSensor:def run(self):print("Alar ...

  8. Python设计模式-桥接模式

    Python设计模式-桥接模式 基于Python3.5.2,代码如下 #coding:utf-8class Shape():name = ""param = "" ...

  9. Python设计模式-代理模式

    Python设计模式-代理模式 基于Python3.5.2,代码如下 #coding:utf-8info_struct = dict() info_struct["addr"] = ...

  10. 设计模式 | 解释器模式及典型应用

    微信原文:设计模式 | 解释器模式及典型应用 博客原文:设计模式 | 解释器模式及典型应用 本文主要介绍解释器模式,在日常开发中,解释器模式的使用频率比较低 解释器模式 解释器模式(Interpret ...

最新文章

  1. 通信系统之信道(二)
  2. Android 开发, Android 安全 精品资料收集 (持续更新...)
  3. Oracle ETL日志审计存储过程示例
  4. JMS学习二(简单的ActiveMQ实例)
  5. Linux学习教程,Linux入门教程(超详细)| 网址推荐
  6. 基于JAVA+SpringMVC+Mybatis+MYSQL的网上相册展示系统
  7. DataGrip 格式化SQL 自定义SQL格式化
  8. mysql中的rman备份与恢复_RMAN备份与恢复实践(转)
  9. python 题库项目_python 题库|刷题
  10. Struts2快速入门,超简单详细的快速入门教程
  11. win10计算机 回收站等怎么放桌面,WIN10如何在桌面删除回收站_win10电脑怎么删除回收站图标-win7之家...
  12. Java后端社招面试经历,不愧是大佬
  13. R7-7735HS和i5-13500H 差距 锐龙R77735HS和酷睿i513500H对比
  14. 李沐动手学深度学习第四章-4.9.环境和分布偏移
  15. uniAPP小程序webview从H5返回小程序不起作用
  16. tcpreplay命令详解
  17. 西门子ET200SP基座单元的区别与分类以及注意事项
  18. [某人的题解]徒步旅行(travel)
  19. 【vue系列-05】vue的生命周期(详解)
  20. Spark - Illegal pattern component: XXX 与org.apache.commons.lang3.time.FastDateFormat incompatible

热门文章

  1. Linux系统编程——多任务的同步与互斥
  2. 手机通讯录联系人恢复,通讯录丢失怎么办
  3. 打造会展资讯库,FoodTalks这样做
  4. yolov5训练时卡住0%解决方案
  5. 我的教师实习实习记录(十二)(终结篇)
  6. Altium DXP 检查布线是否完整并定位未布线网络
  7. python回归算法预测数据_数据回归分类预测的基本算法及python实现
  8. 近期白银期货技术分析!
  9. 利用神经网络让Shader纯数学绘制任意图片
  10. .net 操作 excel