设计处理多种通信协议的类

Rob*_*dor 3 c++ design-patterns server-communication

我正在开发一个 C++ 应用程序,它应该处理多种通信协议(以太网、串行等)。每个通信协议都作为一个特定的类进行处理。为了暴露尽可能少的有关上述类和协议的内部结构和组织的信息,我想以某种方式包装所有这些功能,并提供一些通用的 API,用于通过选定的协议发送数据。

基本上,API应该提供什么(参数不限于此,而是总体思路):

bool sendData(uint8_t* buffer, const size_t& bufferSize);

void receiveData(uint8_t* dataBuffer, size_t& bufferSize);
Run Code Online (Sandbox Code Playgroud)

为上述功能创建通用 API 的最佳方法是什么?如果可能的话,涉及一些设计模式?

问候。

眠りネ*_*ネロク 5

\n

为上述功能创建通用 API 的最佳方法是什么?如果可能的话,涉及一些设计模式?

\n
\n\n

策略模式看起来很适合这种情况。

\n\n

首先,为所有不同的通信策略 定义一个接口Communication

\n\n
class Communication {\npublic:\n   virtual ~CommunicationStrategy() = default;\n   virtual bool sendData(uint8_t* buffer, const size_t& bufferSize) = 0;\n   virtual void receiveData(uint8_t* dataBuffer, size_t& bufferSize) = 0;\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后,您的具体实现 \xe2\x80\x93 即策略\xe2\x80\x93 应从此接口派生:

\n\n
class EthernetCommunication: public Communication {\npublic:\n   // ...\n   bool sendData(uint8_t*, const size_t&) override;\n   void receiveData(uint8_t*, size_t&) override;\n};\n\nclass SerialCommunication: public Communication {\npublic:\n   // ...\n   bool sendData(uint8_t*, const size_t&) override;\n   void receiveData(uint8_t*, size_t&) override;\n};\n\nclass CarrierPigeon: public Communication {\npublic:\n   // ...\n   bool sendData(uint8_t*, const size_t&) override;\n   void receiveData(uint8_t*, size_t&) override;\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

客户端代码将使用(指向)Communication\xe2\x80\x93 的(指针),即接口\xe2\x80\x93,而不是直接使用特定的实现,如EthernetCommunicationSerialCommunicationCarrierPigeon。因此,代码遵循“对接口进行编程,而不是对实现进行编程”的建议。例如,您可能有一个工厂函数,例如:

\n\n
std::unique_ptr<Communication> CreateCommunication();\n
Run Code Online (Sandbox Code Playgroud)\n\n

该工厂函数返回上述策略之一。返回哪种策略可以在运行时确定。

\n\n
std::unique_ptr<Communication> com = CreateCommunication();\n// send data regardless of a particular communication strategy\ncom->sendData(buffer, bufferSize);\n
Run Code Online (Sandbox Code Playgroud)\n\n

这样,上面的代码就不会耦合到任何特定的实现,而仅耦合到Communication所有不同可能的通信策略所共用的接口。

\n\n
\n\n

如果不同的通信策略不需要每个实例的数据,只需使用两个回调而不是一个对象即可:

\n\n
using data_sender_t = bool (*)(uint8_t*, const size_t&);\nusing data_receiver_t = void (*)(uint8_t*, size_t&);\n\n// set these function pointers to the strategy to use\ndata_sender_t data_sender;\ndata_receiver_t data_receiver;\n
Run Code Online (Sandbox Code Playgroud)\n