直譯器模式

weixin_34377065發表於2017-07-13

直譯器模式

1、內容

給定一種語言,定義它的文法表示,並定義一個直譯器,該直譯器使用該表示來解釋語言中的句子。

直譯器模式中會有終結符和非終結符之說,語法也根據兩種終結符,決定語句最終含義。

2、角色

    AbstractExpression: 抽象表示式
    TerminalExpression: 終結符表示式
    NonterminalExpression: 非終結符表示式
    Context: 環境類
    Client: 客戶類
複製程式碼

3、使用場景

1、若一個問題重複發生,可以考慮使用直譯器模式。這點在資料處理和日誌處理過程中使用較多,當資料的需求方需要將資料納為己用時,必須將資料“翻譯”成本系統的資料規格;同樣的道理,日誌分析平臺也需要根據不同的日誌格式翻譯成統一的“語言”。 2、特定語法直譯器。如各種解釋型語言的直譯器,再比如自然語言中基於語法的文字分析等。

**4、優點 **

1、在語法分析的場景中,具有比較好的擴充套件性。規則修改和制訂比較靈活。

5、缺點

1、解釋規則多樣化會導致直譯器的爆炸; 2、直譯器目標比較單一,行為模式比較固定,因而重要的模組中儘量不要使用直譯器模式。

6、程式碼示例

#!/usr/bin/python
#coding:utf8
'''
Interpreter
'''

class Context:
   def __init__(self):
       self.input=""
       self.output=""

class AbstractExpression:
   def Interpret(self,context):
       pass

class 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)
複製程式碼

直譯器模式

識別圖中二維碼,領取python全套視訊資料

相關文章