码迷,mamicode.com
首页 > 其他好文 > 详细

解释器模式

时间:2014-08-23 16:45:11      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   ar   2014   art   div   

模式说明

所谓解释器(Interpreter)就是将一系列指令转化成代码,能够执行的代码。Interpreter本来就有翻译的意思。GoF给它的定义是:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

模式结构图

bubuko.com,布布扣

程序示例

说明:一个上下文类;一个解释器,两个派生解释器

代码:

 1 class Context(object):
 2     def __init__(self, msg):
 3         self._msg=msg
 4     def getmsg(self):
 5         return self._msg
 6 
 7 class Interpretor(object):
 8     def interpret(self):
 9         pass
10 
11 class UpperInterpretor(Interpretor):
12     def __init__(self, context):
13         self._context=context
14         
15     def interpret(self):
16         msg = self._context.getmsg()
17         print str(msg).upper()
18 
19 class LowerInterpretor(Interpretor):
20     def __init__(self, context):
21         self._context=context
22         
23     def interpret(self):
24         msg = self._context.getmsg()
25         print str(msg).lower()
26 
27 if __name__==__main__:
28     context = Context(ABCdef)
29     upper = UpperInterpretor(context)
30     lower = LowerInterpretor(context)
31 
32     upper.interpret()
33     lower.interpret()

运行结果:

bubuko.com,布布扣

参考来源:

http://www.cnblogs.com/chenssy/p/3679190.html

http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

http://www.cnblogs.com/imakoo/articles/2944578.html

解释器模式

标签:style   blog   http   color   使用   ar   2014   art   div   

原文地址:http://www.cnblogs.com/wang-shuai/p/3931403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!