1. 程式人生 > >設計模式-行為型模式,解釋器模式(12)

設計模式-行為型模式,解釋器模式(12)

string alpha 處理 argument exp 如何 command 領域 __str__

解釋器模式(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()

設計模式-行為型模式,解釋器模式(12)