程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python design pattern behavioral pattern Interpreter pattern

編輯:Python

Catalog

List of articles

  • Catalog
  • Interpreter mode
  • Application scenarios
  • Code example

Interpreter mode

Interpreter mode , Developers customize a “ It has meaning ” Language ( Or string ), And set relevant interpretation rules , After entering this string, you can output a recognized interpretation , Or perform actions that the program can understand .

advantage

  1. Good scalability , flexible .
  2. Added new ways to interpret expressions .
  3. Easy to implement simple grammar .

shortcoming

  1. There are few available scenarios .
  2. It's hard to maintain complex grammar .
  3. Interpreter mode causes class inflation .

Application scenarios

  • SQL analysis
  • Symbol processing engine

Code example

Entity role :

  • Terminator expression : Implement the interpretation operations associated with elements in grammar , Usually there is only one terminator expression in an Interpreter pattern , But there are multiple instances , Corresponding to different terminators . The terminator is half the unit of operation in grammar , For example, there is a simple formula R=R1+R2, On the inside R1 and R2 It's the terminator , Corresponding analysis R1 and R2 The interpreter of is the terminator expression .
  • Nonterminal expression : Each rule in grammar corresponds to a nonterminal expression , Nonterminal expressions are usually operators or other keywords in grammar , such as : The formula R=R1+R2 in ,“+” Is a nonterminal , analysis “+” The interpreter of is a nonterminal expression . Nonterminal expressions increase based on the complexity of the logic , In principle, each grammar rule corresponds to a nonterminal expression .
import time
import datetime
""" Realize a simple Chinese programming """
class Code:
""" Custom language """
def __init__(self, text=None):
self.text = text
class InterpreterBase:
""" Custom interpreter base class """
def run(self, code):
pass
class Interpreter(InterpreterBase):
""" Implement the interpreter method , Implement the terminator expression dictionary """
def run(self, code):
code = code.text
code_dict = {
' Get the current timestamp ': time.time(), " Get current date ": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
print(code_dict.get(code))
if __name__ == '__main__':
test = Code()
test.text = ' Get the current timestamp '
data1 = Interpreter().run(test)
test.text = ' Get current date '
data2 = Interpreter().run(test)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved