【发布时间】:2018-03-18 13:31:11
【问题描述】:
我有一个抽象类Interface。一个接口有一个read 方法读取数据并解析它,还有一个getData 方法实际返回解析后的数据。每个接口都有一个Parser 对象来进行实际的解析。解析器有一个 parse 方法和解析数据的 getter。USBInterface 和 SerialInterface 类继承自 Interface。
问题:
如何为 USBInterface 和 SerialInterface 使用不同的解析器?
有两个解析器,USBParser 和 SerialParser,它们继承自 Parser。
我当前的解决方案在接口构造函数中初始化的Interface 基类中使用Parser 引用,但我不确定这是否是最佳方法。
class Parser {
public:
Parser() {}
int getData() {
return data;
}
protected:
int data;
};
class USBParser : public Parser {
public:
USBParser() {}
bool parse(uint8_t *usbpacket) {
data = usbpacket[1]; // Do the actual parsing here
return true; // Return true if data is complete
}
};
class SerialParser : public Parser {
public:
SerialParser() {}
bool parse(uint8_t databyte) {
data = databyte; // Do the actual parsing here
return true; // Return true if data is complete
}
};
class Interface {
public:
Interface(Parser &parser) : parser(parser) {}
virtual bool read() = 0;
int getData() {
return parser.getData();
}
protected:
Parser &parser;
};
class USBInterface : public Interface {
public:
USBInterface() : Interface(parser) {}
bool read() {
uint8_t usbpacket[4] = {0x00, 0x01, 0x02, 0x03}; // Read raw data from USB
return parser.parse(usbpacket);
}
private:
USBParser parser;
};
class SerialInterface : public Interface {
public:
SerialInterface() : Interface(parser) {}
bool read() {
uint8_t databyte = 0xFF; // Read raw data from serial port
return parser.parse(databyte);
}
private:
SerialParser parser;
};
int main() {
USBInterface usb;
SerialInterface serial;
if (usb.read())
println(usb.getData());
if (serial.read())
println(serial.getData());
}
我的方法有什么缺陷,还是有更好的方法?
【问题讨论】:
-
这个问题是基于意见的。您的方法将起作用唯一的缺陷是您的示例不需要任何继承。您的代码看起来过于复杂,没有任何理由,只是希望添加继承。
-
@Serge:感谢您的评论。我发布的代码已简化。继承的目标是对接口类型进行抽象。程序的其余部分不关心是使用 USB 接口还是串行接口,它只需要能够从接口读取数据。
标签: c++ oop inheritance abstract-class