設計模式 直譯器模式

2021-10-11 18:05:27 字數 2026 閱讀 8633

#include

"iostream"

#include

"vector"

#include

"string"

using

namespace std;

// 抽象表示式類

class

abstractnode

// 宣告抽象介面

virtual

char

interpret()

=0;}

;// 終結符表示式:valuenode

class

valuenode

:public abstractnode

valuenode

(int ivalue)

// 實現解釋操作

char

interpret()

private

:int value;};

// 終結符表示式:operationnode

class

operatornode

:public abstractnode

operatornode

(string iop)

// 實現解釋操作

char

interpret()

else

if(op ==

"or"

)return0;

}private

: string op;};

// 非終結符表示式:sentencenode

class

sentencenode

:public abstractnode

sentencenode

(abstractnode *ileftnode,

abstractnode *irightnode, abstractnode* ioperatornode)

char

interpret()

else

return0;

}private

: abstractnode *leftnode;

abstractnode *rightnode;

abstractnode *operatornode;};

// 處理者

class

handler

void

setinput

(string iinput)

void

handle()

for(

int i =

0; i < inputlist.

size()

-2; i +=2

) string tmpres = inputlist[inputlist.

size()

-1];

if(tmpres ==

"1")

else

if(tmpres ==

"0")

else

this

->

output()

;}void

output()

private

: string input;

char result;

};

int

main()

執行結果:

1and1=

11and0=0

0and1=

00and0=0

0or0=

00or1

=11or

0=11

or1=1

1and0or

1=10

or0and1=0

1or1and

1and0=

00and1

and1

and1=0

0and

1and

1and1or

1or0and1=

1請按任意鍵繼續.

..

設計模式

設計模式 直譯器模式

未來機器智慧型化已然成為趨勢,現在手機都能聽懂英語和普通話,那我大中華幾萬種方言的被智慧型化也許也是趨勢,我們的方言雖然和普通話相似,但是還是不一樣的。這可能需要乙個新的語法分析器來幫助我們。我們的直譯器模式就是描述了如何為簡單的語言定義乙個文法,如何在該語言中表示乙個句子,以及如何解釋這些句子。但...

設計模式 直譯器模式

直譯器模式 給定乙個語言,定義它的文法的一種表示,並定義乙個直譯器,這個直譯器使用該表示來解釋語言中的句子。如果一種特定型別的問題發生的頻率足夠高,那麼可能就值得將該問題的各個例項表述為乙個簡單語言中的句子。這樣就可以構建乙個直譯器,該直譯器通過解釋這些句子來解決該問題。當有乙個語言需要解釋執行,並...

設計模式 直譯器模式

直譯器模式 interpreter pattern 提供了評估語言的語法或表示式的方式,它屬於行為型模式。這種模式實現了乙個表示式介面,該介面解釋乙個特定的上下文。這種模式被用在 sql 解析 符號處理引擎等。給定乙個語言,定義它的文法表示,並定義乙個直譯器,這個直譯器使用該標識來解釋語言中的句子。...