我正在开发一个C++应用程序,它应该处理多个通信协议(以太网、串行等)。每个通信协议都作为特定的类处理。为了尽可能少地公开有关上述类和协议的内部结构和组织的信息,我想以某种方式封装所有这些功能,并为通过选定的协议发送数据提供一些通用的API。
基本上,API应该提供什么(参数不限于此,而是一般的想法):
bool sendData(uint8_t* buffer, const size_t& bufferSize);
void receiveData(uint8_t* dataBuffer, size_t& bufferSize);
为上述功能创建通用API的最佳方法是什么,如果可能的话,涉及到一些设计模式?
致以问候。
发布于 2020-05-18 06:03:27
为上述功能创建通用API的最佳方法是什么,如果可能的话,涉及到一些设计模式?
在这个场景中,战略模式看起来很合适。
首先,为所有不同的通信起点定义一个接口,Communication
class Communication {
public:
virtual ~CommunicationStrategy() = default;
virtual bool sendData(uint8_t* buffer, const size_t& bufferSize) = 0;
virtual void receiveData(uint8_t* dataBuffer, size_t& bufferSize) = 0;
};
然后,您的具体实现--即策略--应该从这个接口派生出来:
class EthernetCommunication: public Communication {
public:
// ...
bool sendData(uint8_t*, const size_t&) override;
void receiveData(uint8_t*, size_t&) override;
};
class SerialCommunication: public Communication {
public:
// ...
bool sendData(uint8_t*, const size_t&) override;
void receiveData(uint8_t*, size_t&) override;
};
class CarrierPigeon: public Communication {
public:
// ...
bool sendData(uint8_t*, const size_t&) override;
void receiveData(uint8_t*, size_t&) override;
};
客户端代码将使用(指向) Communication
(即接口),而不是直接使用特定的实现,如EthernetCommunication
、SerialCommunication
或CarrierPigeon
。因此,代码遵循编程到接口,而不是执行通知。例如,您可能有一个工厂函数,如:
std::unique_ptr<Communication> CreateCommunication();
此工厂函数返回上述策略之一。在运行时可以确定返回的策略。
std::unique_ptr<Communication> com = CreateCommunication();
// send data regardless of a particular communication strategy
com->sendData(buffer, bufferSize);
这样,上面的代码并不耦合到任何特定的实现,而是只耦合到接口Communication
,这是所有不同的可能的通信策略所共有的。
如果不同的通信策略不需要每个实例数据,那么只需要两个回调而不是一个对象就可以了:
using data_sender_t = bool (*)(uint8_t*, const size_t&);
using data_receiver_t = void (*)(uint8_t*, size_t&);
// set these function pointers to the strategy to use
data_sender_t data_sender;
data_receiver_t data_receiver;
https://stackoverflow.com/questions/61871193
复制