解譯器模式:給定一個語言,定義它文法的一種表示,並定義一個解譯器。這個解譯器使用該‘表示’來解釋語言中的句子。
應用情境:如果一種特定類型的問題發生的頻率足夠高,那麼可能就值得將該問題的各個執行個體表述為一個簡單語言中的句子。這樣就可以構建一個解譯器,該解譯器通過解釋這些句子來解決該問題。比如“正常運算式”。
#encoding=utf-8##by panda#解譯器模式def printInfo(info): print unicode(info, 'utf-8').encode('gbk'),#上下文類:演奏內容class PlayContext(): text = None PlayText = None#抽象運算式類class Expression(): def Interpret(self, context): if len(context.PlayText) == 0: return else: playKey = context.PlayText[0:1] context.PlayText = context.PlayText[2:] tmp = context.PlayText.index(' ') #找出第一個空格出現的位置 playValue = context.PlayText[0:tmp] context.PlayText = context.PlayText[tmp+1:] self.Excute(playKey,playValue) def Excute(self,playKey,playValue): pass#音高class Pitch(Expression): pitch = None def Excute(self, key, value): value = int(value) if value == 1: self.pitch = '低音' elif value == 2: self.pitch = '中音' elif value == 3: self.pitch = '高音' printInfo(self.pitch) #音符class Note(Expression): Notes = { 'C':1, 'D':2, 'E':3, 'F':4, 'G':5, 'A':6, 'B':7, } note = None def Excute(self, key, value): self.note = self.Notes[key] printInfo('%d' % self.note)def clientUI(): context = PlayContext() context.PlayText = "O 2 E 0.5 G 0.5 A 3 E 0.5 G 0.5 D 3 E 0.5 G 0.5 A 0.5 O 3 C 1 O 2 A 0.5 G 1 C 0.5 E 0.5 D 3 " expression = None; while(len(context.PlayText) > 0): str = context.PlayText[0:1]; if(str == 'O'): expression = Pitch() elif(str == 'C' or str == 'D' or str == 'E' or str == 'F' or str == 'G' or str == 'A' or str == 'B' or str == 'P'): expression = Note() expression.Interpret(context) returnif __name__ == '__main__': clientUI();
類圖: