23种设计模式 - 迭代器模式

时间:2025-02-20 15:16:28
#include #include #include // G代码指令类 class GCodeCommand { public: std::string type; // 指令类型(如G00) float x, y; // 坐标参数 GCodeCommand(const std::string& t, float xVal, float yVal) : type(t), x(xVal), y(yVal) {} }; // 抽象迭代器 class Iterator { public: virtual bool hasNext() = 0; virtual GCodeCommand next() = 0; virtual ~Iterator() = default; }; // 具体迭代器:G代码指令迭代器 class GCodeIterator : public Iterator { private: std::vector& commands; size_t currentPos; public: GCodeIterator(std::vector& cmds) : commands(cmds), currentPos(0) {} bool hasNext() override { return currentPos < commands.size(); } GCodeCommand next() override { return commands[currentPos++]; } }; // 抽象聚合类 class GCodeCollection { public: virtual Iterator* createIterator() = 0; virtual ~GCodeCollection() = default; }; // 具体聚合类:存储G代码指令 class ConcreteGCodeCollection : public GCodeCollection { private: std::vector commands; public: void addCommand(const GCodeCommand& cmd) { commands.push_back(cmd); } Iterator* createIterator() override { return new GCodeIterator(commands); } }; // 客户端代码 int main() { ConcreteGCodeCollection gcodeList; gcodeList.addCommand(GCodeCommand("G00", 100, 200)); // 快速定位 gcodeList.addCommand(GCodeCommand("G01", 200, 300)); // 直线插补 Iterator* it = gcodeList.createIterator(); while (it->hasNext()) { GCodeCommand cmd = it->next(); std::cout << "执行指令: " << cmd.type << " X" << cmd.x << " Y" << cmd.y << std::endl; // 实际数控系统会调用机床控制接口执行指令 } delete it; return 0; }