当前位置:   article > 正文

《设计模式的艺术》笔记 - 解释器模式

《设计模式的艺术》笔记 - 解释器模式

介绍

        解释器模式定义一个语言的文法,并且建立一个解释器来解释该语言中的句子,这里的“语言”是指使用规定格式和语法的代码。解释器模式是一种类行为型模式。

实现

myclass.h

  1. //
  2. // Created by yuwp on 2024/1/12.
  3. //
  4. #ifndef DESIGNPATTERNS_MYCLASS_H
  5. #define DESIGNPATTERNS_MYCLASS_H
  6. #include <iostream>
  7. #include <unordered_map>
  8. #include <atomic>
  9. #include <vector>
  10. #include <memory>
  11. class Context {
  12. };
  13. class AbstractExpression { // 抽象表达式
  14. public:
  15. virtual float interpret() = 0;
  16. };
  17. class Add : public AbstractExpression { // 非终结符表达式
  18. public:
  19. Add(std::shared_ptr<AbstractExpression> left, std::shared_ptr<AbstractExpression> right);
  20. float interpret() override;
  21. private:
  22. std::shared_ptr<AbstractExpression> m_left;
  23. std::shared_ptr<AbstractExpression> m_right;
  24. };
  25. class Substract : public AbstractExpression { // 非终结符表达式
  26. public:
  27. Substract(std::shared_ptr<AbstractExpression> left, std::shared_ptr<AbstractExpression> right);
  28. float interpret() override;
  29. private:
  30. std::shared_ptr<AbstractExpression> m_left;
  31. std::shared_ptr<AbstractExpression> m_right;
  32. };
  33. class Multiply : public AbstractExpression { // 非终结符表达式
  34. public:
  35. Multiply(std::shared_ptr<AbstractExpression> left, std::shared_ptr<AbstractExpression> right);
  36. float interpret() override;
  37. private:
  38. std::shared_ptr<AbstractExpression> m_left;
  39. std::shared_ptr<AbstractExpression> m_right;
  40. };
  41. class Division : public AbstractExpression { // 非终结符表达式
  42. public:
  43. Division(std::shared_ptr<AbstractExpression> left, std::shared_ptr<AbstractExpression> right);
  44. float interpret() override;
  45. private:
  46. std::shared_ptr<AbstractExpression> m_left;
  47. std::shared_ptr<AbstractExpression> m_right;
  48. };
  49. class Negative : public AbstractExpression { // 非终结符表达式
  50. public:
  51. Negative(std::shared_ptr<AbstractExpression> exp);
  52. float interpret() override;
  53. private:
  54. std::shared_ptr<AbstractExpression> m_exp;
  55. };
  56. class Value : public AbstractExpression {
  57. public:
  58. Value(float val);
  59. float interpret() override;
  60. private:
  61. float m_val;
  62. };
  63. class ExpressionParser {
  64. public:
  65. ExpressionParser(const std::string &expStr);
  66. std::shared_ptr<AbstractExpression> getExpression();
  67. private:
  68. void popOperation();
  69. std::vector<char> m_ops;
  70. std::vector<std::shared_ptr<AbstractExpression>> m_vals;
  71. };
  72. #endif //DESIGNPATTERNS_MYCLASS_H

myclass.cpp

  1. //
  2. // Created by yuwp on 2024/1/12.
  3. //
  4. #include "myclass.h"
  5. #include <thread>
  6. #include <unistd.h>
  7. Add::Add(std::shared_ptr<AbstractExpression> left, std::shared_ptr<AbstractExpression> right) {
  8. m_left = left;
  9. m_right = right;
  10. }
  11. float Add::interpret() {
  12. return m_left->interpret() + m_right->interpret();
  13. }
  14. Substract::Substract(std::shared_ptr<AbstractExpression> left, std::shared_ptr<AbstractExpression> right) {
  15. m_left = left;
  16. m_right = right;
  17. }
  18. float Substract::interpret() {
  19. return m_left->interpret() - m_right->interpret();
  20. }
  21. Multiply::Multiply(std::shared_ptr<AbstractExpression> left, std::shared_ptr<AbstractExpression> right) {
  22. m_left = left;
  23. m_right = right;
  24. }
  25. float Multiply::interpret() {
  26. return m_left->interpret() * m_right->interpret();
  27. }
  28. Division::Division(std::shared_ptr<AbstractExpression> left, std::shared_ptr<AbstractExpression> right) {
  29. m_left = left;
  30. m_right = right;
  31. }
  32. float Division::interpret() {
  33. return m_left->interpret() / m_right->interpret();
  34. }
  35. Negative::Negative(std::shared_ptr<AbstractExpression> exp) {
  36. m_exp = exp;
  37. }
  38. float Negative::interpret() {
  39. return -m_exp->interpret();
  40. }
  41. Value::Value(float val) {
  42. m_val = val;
  43. }
  44. float Value::interpret() {
  45. return m_val;
  46. }
  47. ExpressionParser::ExpressionParser(const std::string &expStr) {
  48. char prev = '\0', c, op;
  49. std::shared_ptr<AbstractExpression> exp;
  50. std::unordered_map<char, char> brackets = {{'}', '{'}, {']', '['}, {')', '('}};
  51. float val;
  52. for (int i = 0; i < expStr.length(); ++i) {
  53. c = expStr[i];
  54. if (c == ' ') {
  55. continue;
  56. } else if (c == '+') {
  57. while (m_ops.size() > 0 && m_ops[m_ops.size() - 1] != '{' && m_ops[m_ops.size() - 1] != '[' && m_ops[m_ops.size() - 1] != '(') {
  58. popOperation();
  59. }
  60. m_ops.push_back(c);
  61. prev = c;
  62. } else if (c == '-') {
  63. if (prev == '\0' || prev == '{' || prev == '[' || prev == '(') {
  64. m_vals.push_back(0);
  65. } else {
  66. while (m_ops.size() > 0 && m_ops[m_ops.size() - 1] != '{' && m_ops[m_ops.size() - 1] != '[' && m_ops[m_ops.size() - 1] != '(') {
  67. popOperation();
  68. }
  69. }
  70. m_ops.push_back(c);
  71. prev = c;
  72. } else if (c == '*' || c == '/') {
  73. if (m_ops.size() > 0 && (m_ops[m_ops.size() - 1] == '*' || m_ops[m_ops.size() - 1] == '/')) {
  74. popOperation();
  75. }
  76. m_ops.push_back(c);
  77. prev = c;
  78. } else if (c == '{' || c == '[' || c == '(') {
  79. m_ops.push_back(c);
  80. prev = c;
  81. } else if (c == '}' || c == ']' || c == ')') {
  82. while (m_ops.size() > 0) {
  83. op = m_ops[m_ops.size() - 1];
  84. if (op == brackets[c]) {
  85. m_ops.pop_back();
  86. break;
  87. } else {
  88. popOperation();
  89. }
  90. }
  91. } else if (c >= '0' && c <= '9'){
  92. char buf[128];
  93. int j = 0;
  94. while (c == '.' || (c >= '0' && c <= '9')) {
  95. buf[j] = c;
  96. j++;
  97. i++;
  98. c = expStr[i];
  99. }
  100. prev = '0';
  101. --i;
  102. buf[j] = '\0';
  103. val = atof(buf);
  104. exp.reset(new Value(val));
  105. m_vals.push_back(exp);
  106. }
  107. }
  108. if (m_ops.size() > 0) {
  109. popOperation();
  110. }
  111. if (m_vals.size() != 1) {
  112. goto failed;
  113. }
  114. return;
  115. failed:
  116. m_vals.resize(1);
  117. m_vals[0] = nullptr;
  118. }
  119. void ExpressionParser::popOperation() {
  120. char op = m_ops[m_ops.size() - 1];
  121. std::shared_ptr<AbstractExpression> exp;
  122. if (op == '+') {
  123. exp.reset(new Add(m_vals[m_vals.size() - 2], m_vals[m_vals.size() - 1]));
  124. } else if (op == '-') {
  125. exp.reset(new Substract(m_vals[m_vals.size() - 2], m_vals[m_vals.size() - 1]));
  126. } else if (op == '*') {
  127. exp.reset(new Multiply(m_vals[m_vals.size() - 2], m_vals[m_vals.size() - 1]));
  128. } else if (op == '/') {
  129. exp.reset(new Division(m_vals[m_vals.size() - 2], m_vals[m_vals.size() - 1]));
  130. } else {
  131. return;
  132. }
  133. m_ops.pop_back();
  134. m_vals.pop_back();
  135. m_vals.pop_back();
  136. m_vals.push_back(exp);
  137. }
  138. std::shared_ptr<AbstractExpression> ExpressionParser::getExpression() {
  139. return m_vals[0];
  140. }

main.cpp

  1. #include <iostream>
  2. #include <mutex>
  3. #include "myclass.h"
  4. int main() {
  5. ExpressionParser *expressionParser = new ExpressionParser("(1+2)*(6-2)/2+1");
  6. auto exp = expressionParser->getExpression();
  7. if (exp) {
  8. std::cout << exp->interpret() << std::endl;
  9. } else {
  10. std::cout << 0 << std::endl;
  11. }
  12. return 0;
  13. }

总结

优点

        1. 易于改变和扩展文法。由于在解释器模式中使用类来表示语言的文法规则,因此可以通过继承等机制来改变或扩展文法。

        2. 每一条文法规则都可以表示为一个类,因此可以方便地实现一个简单的语言。

        3. 实现文法较为容易。在抽象语法树中每一个表达式节点类的实现方式都是相似的,这些类的代码编写都不会特别复杂,还可以通过一些工具自动生成节点类代码。

        4. 增加新的解释表达式较为方便。如果用户需要增加新的解释表达式只需要对应增加一个新的终结符表达式或非终结符表达式类,原有表达式类代码无须修改,符合开闭原则。

缺点

        1. 对于复杂文法难以维护。在解释器模式中,每一条规则至少需要定义一个类,因此如果一种语言包含太多文法规则,类的个数将会急剧增加,导致系统难以管理和维护,此时可以考虑使用语法分析程序等方式来取代解释器模式。

        2. 执行效率较低。由于在解释器模式中使用了大量的循环和递归调用,因此在解释较为复杂的句子时其速度很慢,而且代码的调试过程也比较麻烦。

适用场景

        1. 可以将一个需要解释执行的语言中的句子表示为一个抽象语法树。

        2. 一些重复出现的问题可以用一种简单的语言来进行表达。

        3. 一个语言的文法较为简单。

        4. 执行效率不是关键问题。(注:高效的解释器通常不是通过直接解释抽象语法树来实现的,而是需要将它们转换成其他形式,使用解释器模式的执行效率并不高。)

练习

myclass.h

  1. //
  2. // Created by yuwp on 2024/1/12.
  3. //
  4. #ifndef DESIGNPATTERNS_MYCLASS_H
  5. #define DESIGNPATTERNS_MYCLASS_H
  6. #include <iostream>
  7. #include <unordered_map>
  8. #include <atomic>
  9. #include <vector>
  10. #include <memory>
  11. /**
  12. * COPY VIEW FROM srcDB TO desDB 表示将数据库srcDB中的所有视图对象都复制至数据库desDB
  13. * MOVE TABLE Student FROM srcDB TO desDB 表示将数据库srcDB中的Student表移动至数据库desDB
  14. * expression ::= operation object FROM string to string
  15. * operation ::= 'COPY' | 'MOVE'
  16. * object ::= 'VIEW' | 'TABLE string'
  17. */
  18. class AbstractNode {
  19. public:
  20. virtual std::string interpret() = 0;
  21. };
  22. class SentenceNode : public AbstractNode { // expression 简单句子,非终结符表达式
  23. public:
  24. SentenceNode(std::shared_ptr<AbstractNode> operation, std::shared_ptr<AbstractNode> object, std::string &srcDB, std::string &desDB);
  25. std::string interpret() override;
  26. private:
  27. std::shared_ptr<AbstractNode> m_operation;
  28. std::shared_ptr<AbstractNode> m_object;
  29. std::string m_srcDB;
  30. std::string m_desDB;
  31. };
  32. class OperationNode : public AbstractNode { // 终结符表达式
  33. public:
  34. OperationNode(std::string operation);
  35. std::string interpret() override;
  36. private:
  37. std::string m_operation;
  38. };
  39. class ObjectNode : public AbstractNode { // 终结符表达式
  40. public:
  41. ObjectNode(std::string object, std::string name = "");
  42. std::string interpret() override;
  43. private:
  44. std::string m_object;
  45. std::string m_name;
  46. };
  47. class InstructionHandler {
  48. public:
  49. void handle(std::string &instruction);
  50. std::string output();
  51. private:
  52. std::shared_ptr<AbstractNode> m_node;
  53. };
  54. #endif //DESIGNPATTERNS_MYCLASS_H

myclass.cpp

  1. //
  2. // Created by yuwp on 2024/1/12.
  3. //
  4. #include "myclass.h"
  5. #include <thread>
  6. #include <unistd.h>
  7. #include <sstream>
  8. SentenceNode::SentenceNode(std::shared_ptr<AbstractNode> operation, std::shared_ptr<AbstractNode> object,
  9. std::string &srcDB, std::string &desDB) {
  10. m_operation = operation;
  11. m_object = object;
  12. m_srcDB = srcDB;
  13. m_desDB = desDB;
  14. }
  15. std::string SentenceNode::interpret() {
  16. return "将" + m_srcDB + "的" + m_object->interpret() + m_operation->interpret() + "到" + m_desDB;
  17. }
  18. OperationNode::OperationNode(std::string operation) {
  19. m_operation = operation;
  20. }
  21. std::string OperationNode::interpret() {
  22. if (m_operation == "COPY") {
  23. return "拷贝";
  24. } else if (m_operation == "MOVE") {
  25. return "移动";
  26. } else {
  27. return "无效指令";
  28. }
  29. }
  30. ObjectNode::ObjectNode(std::string object, std::string name) {
  31. m_object = object;
  32. m_name = name;
  33. }
  34. std::string ObjectNode::interpret() {
  35. if (m_object == "VIEW") {
  36. return "视图";
  37. } else if (m_object == "TABLE") {
  38. return m_name + "表";
  39. } else {
  40. return "无效指令";
  41. }
  42. }
  43. void InstructionHandler::handle(std::string &instruction) {
  44. std::istringstream iss(instruction);
  45. std::string token, token2, srcDB, desDB;
  46. std::shared_ptr<AbstractNode> op, obj;
  47. int i = 0;
  48. while (iss >> token) {
  49. if (token == "TO") {
  50. continue;
  51. } else if (token == "FROM") {
  52. if (i == 1) {
  53. obj.reset(new ObjectNode(token2, ""));
  54. ++i;
  55. }
  56. continue;
  57. }
  58. if (i == 0) {
  59. op.reset(new OperationNode(token));
  60. ++i;
  61. } else if (i == 1) {
  62. if (token2.length() <= 0) {
  63. token2 = token;
  64. continue;
  65. } else {
  66. obj.reset(new ObjectNode(token2, token));
  67. ++i;
  68. }
  69. } else if (i == 2){
  70. srcDB = token;
  71. ++i;
  72. } else if (i == 3) {
  73. desDB = token;
  74. ++i;
  75. }
  76. }
  77. m_node.reset(new SentenceNode(op, obj, srcDB, desDB));
  78. }
  79. std::string InstructionHandler::output() {
  80. return m_node->interpret();
  81. }

main.cpp

  1. #include <iostream>
  2. #include <mutex>
  3. #include "myclass.h"
  4. int main() {
  5. InstructionHandler *instructionHandler = new InstructionHandler();
  6. std::string ins = "COPY VIEW FROM AA_DB TO BB_DB";
  7. instructionHandler->handle(ins);
  8. std::cout << instructionHandler->output() << std::endl;
  9. ins = "COPY TABLE student FROM AA_DB TO BB_DB";
  10. instructionHandler->handle(ins);
  11. std::cout << instructionHandler->output() << std::endl;
  12. delete instructionHandler;
  13. return 0;
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/41941
推荐阅读
相关标签
  

闽ICP备14008679号