模式定義
解釋器模式(Interpreter Pattern)是一種行為型設計模式,用于為特定語言(如數控系統的G代碼)定義文法規則,并構建解釋器來解析和執行該語言的語句。它通過將語法規則分解為多個類,實現復雜指令的逐層解析。
模式結構
抽象表達式(Abstract Expression)
- 定義
interpret()
接口,聲明解釋操作的抽象方法(如void interpret(Context& context)
)。
終結符表達式(Terminal Expression) - 實現文法中的基本元素(如G代碼指令
G00
、G01
),直接處理具體操作。
非終結符表達式(Non-terminal Expression) - 處理復合語法結構(如嵌套指令組合),通過遞歸調用子表達式實現復雜邏輯。
上下文(Context) - 存儲解釋器所需的全局信息(如機床坐標、刀具狀態)。
適用場景
數控系統G代碼解析:將G00 X100 Y200
等指令轉換為機床運動控制。
數學公式計算:解析并執行如(3+5)*2
的表達式。
自定義腳本引擎:實現簡單控制邏輯的腳本語言。
C++示例(數控G代碼解析)
場景說明:
設計一個解釋器,解析數控系統的G代碼指令(如G00
快速定位、G01
直線插補),并更新機床坐標。
#include
#include
#include
#include // 上下文類:存儲機床坐標
class Context {
public:float x, y;Context() : x(0), y(0) {}
};// 抽象表達式
class Expression {
public:virtual void interpret(Context& context) = 0;virtual ~Expression() = default;
};// 終結符表達式:G00指令(快速移動)
class G00Command : public Expression {
private:float targetX, targetY;
public:G00Command(float x, float y) : targetX(x), targetY(y) {}void interpret(Context& context) override {context.x = targetX;context.y = targetY;std::cout << "快速定位至 (" << context.x << ", " << context.y << ")\n";}
};// 終結符表達式:G01指令(直線插補)
class G01Command : public Expression {
private:float targetX, targetY;
public:G01Command(float x, float y) : targetX(x), targetY(y) {}void interpret(Context& context) override {context.x = targetX;context.y = targetY;std::cout << "直線插補至 (" << context.x << ", " << context.y << ")\n";}
};// 解析器:將字符串指令轉換為表達式對象
Expression* parseCommand(const std::string& input) {std::istringstream iss(input);std::string cmd;float x, y;iss >> cmd >> x >> y;if (cmd == "G00") return new G00Command(x, y);else if (cmd == "G01") return new G01Command(x, y);return nullptr;
}// 客戶端使用
int main() {Context context;std::string code = "G00 100 200\nG01 300 150"; // 模擬G代碼輸入std::istringstream stream(code);std::string line;while (std::getline(stream, line)) {Expression* expr = parseCommand(line);if (expr) {expr->interpret(context);delete expr;}}return 0;
}
代碼解析
上下文類:存儲機床的當前坐標x
和y
。
表達式類:
G00Command
和G01Command
為終結符表達式,直接修改坐標并輸出動作。
解析邏輯:parseCommand
將輸入字符串拆解為指令和參數,生成對應表達式對象。
執行過程:逐行解析G代碼,調用interpret()
更新坐標狀態。