20-Python與設計模式--解釋器模式
一、模拟吉他
要開發一個自動識别譜子的吉他模拟器,達到錄入譜即可按照譜發聲的效果。除了發聲裝置外(假設已完成),最重要的就是讀譜和譯譜能力了。分析其需求,整個過程大緻上分可以分為兩部分:根據規則翻譯譜的内容;根據翻譯的内容演奏。我們用一個解釋器模型來完成這個功能。
class PlayContext():
play_text = None
class Expression():
def interpret(self, context):
if len(context.play_text) == 0:
return
else:
play_segs=context.play_text.split(" ")
for play_seg in play_segs:
pos=0
for ele in play_seg:
if ele.isalpha():
pos+=1
continue
break
play_chord = play_seg[0:pos]
play_value = play_seg[pos:]
self.execute(play_chord,play_value)
def execute(self,play_key,play_value):
pass
class NormGuitar(Expression):
def execute(self, key, value):
print "Normal Guitar Playing--Chord:%s Play Tune:%s"%(key,value)
PlayContext類為譜的内容,這裡僅含一個字段,沒有方法。Expression即表達式,裡面僅含兩個方法,interpret負責轉譯譜,execute則負責演奏;NormGuitar類覆寫execute,以吉他 的方式演奏。
業務場景如下:
if __name__=="__main__":
context = PlayContext()
context.play_text = "C53231323 Em43231323 F43231323 G63231323"
guitar=NormGuitar()
guitar.interpret(context)
列印如下:
Normal Guitar Playing--Chord:C Play Tune:53231323
Normal Guitar Playing--Chord:Em Play Tune:43231323
Normal Guitar Playing--Chord:F Play Tune:43231323
Normal Guitar Playing--Chord:G Play Tune:63231323
二、解釋器模式
解釋器模式定義如下:給定一種語言,定義它的文法表示,并定義一個解釋器,該解釋器使用該表示來解釋語言中的句子。典型的解釋器模式中會有終結符和非終結符之說,文法也根據兩種終結符,決定語句最終含義。上例中,非終結符就是空格,終結符就是整個句尾。