This article mainly introduces the simple program example of interpreter mode in Python Design Mode Programming. The Interpreter mode emphasizes the use of abstract classes to express the functions to be implemented in the program, if you need it, you can refer to the following pattern features: for a given language, define a syntax expression and define an interpreter. This interpreter uses this representation to explain sentences in the language.
Let's take a look at the following program structure:
class Context: def __init__(self): self.input="" self.output=""class AbstractExpression: def Interpret(self,context): passclass 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)
The class diagram it shows is as follows:
Let's look at an example:
# Encoding = UTF-8 ## by panda # interpreter mode def printInfo (info): print unicode (info, 'utf-8 '). encode ('gbk'), # context class: Playing content class PlayContext (): text = None PlayText = None # Abstract Expression 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 ('') # locate the position where the first space appears playValue = context. playText [0: tmp] context. playText = context. playText [tmp + 1:] self. excute (playKey, playValue) def Excute (self, playKey, playValue): pass # Pitch class pitch (Expression): Pitch = None def Excute (self, key, value ): value = int (value) if value = 1: self. pitch = 'bass 'elif value = 2: self. pitch = 'sound' elif value = 3: self. pitch = 'tweeter 'printinfo (self. pitch) # Note 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.5G 0.5 A 3 E 0.5G 0.5 D 3 E 0.5G 0.5 A 0.5 O 3 C 1 O 2 A 0.5G 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 ();
Class diagram: