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 :
Good scalability , flexible .
Added new ways to interpret expressions .
Easy to implement simple grammar .
shortcoming :
There are few available scenarios .
It's hard to maintain complex grammar .
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)