Interpreter mode:Given a language, it defines a syntax expression and an interpreter. This interpreter uses this 'representation' to explain sentences in the language.
Application scenarios: If a particular type of problem occurs frequently enough, it may be worthwhile to express each instance of the problem as a sentence in a simple language. In this way, an interpreter can be built to solve the problem by interpreting these sentences. For example, "normal expression ".
# 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) returnif _ name _ = '_ main _': clientui ();
Class Diagram: