python设计模式编程中解释器模式的简单程序示例分享

模式特点:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

我们来看一下下面这样的程序结构:

class context:
def __init__(self):
self.input=””
self.output=””
class abstractexpression:
def interpret(self,context):
pass
class expression(abstractexpression):
def interpret(self,context):
print “terminal interpret”
class nonterminalexpression(abstractexpression):
def interpret(self,context):
print “nonterminal interpret”
if __name__ == “__main__”:
context= “”
c = []
c = c + [expression()]
c = c + [nonterminalexpression()]
c = c + [expression()]
c = c + [expression()]
for a in c:
a.interpret(context)

那么它所体现出的类图是这样的:

201632150316773.png (682×450)

再来看一个例子:

#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)
return
if __name__ == ‘__main__’:
clientui();

类图:

201632150401221.gif (695×368)

Posted in 未分类