我是靠谱客的博主 聪慧火,这篇文章主要介绍C++23种设计模式(23)-解释器模式,现在分享给大家,希望可以做个参考。

解释器模式,给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。解释器模式解决的问题是,如果一种特定类型的问题发生的频率足够高,那么可能就只得将该问题的各个示例表述为一个简单语言中的句子。这样就可以构建一个解释器,该解释器通过解释这些句子来解决问题。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream> #include <list> #include<vector> #include<string> using namespace std; class Context { private: std::string m_strInput; std::string m_strOutput; public: void setExpression(std::string str) { m_strInput = str; } }; class Expression { public: virtual void Interpret(Context * context) = 0; }; class TerminalExpression : public Expression { public: void Interpret(Context * context) { std::cout << "TerminalExpression!" << std::endl; } }; class NonterminalExpression : public Expression { public: void Interpret(Context * context) { std::cout << "NonterminalExpression!" << std::endl; } }; int main() { using namespace std; // 解释器模式 Context * pContext = new Context(); pContext->setExpression("Expression......"); Expression * pNon = new NonterminalExpression(); Expression * p = new TerminalExpression(); // 根据Expression中的内容判断采用那种表达式解析 pNon->Interpret(pContext); p->Interpret(pContext); delete p; delete pNon; delete pContext; getchar(); return 0; }

在这里插入图片描述

最后

以上就是聪慧火最近收集整理的关于C++23种设计模式(23)-解释器模式的全部内容,更多相关C++23种设计模式(23)-解释器模式内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(97)

评论列表共有 0 条评论

立即
投稿
返回
顶部