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

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

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

void receiveData(uint8_t* dataBuffer, size_t& bufferSize);

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

问候。

最佳答案



The Strategy Pattern 看起来很适合这种情况。

首先,为所有不同的通信策略定义一个接口(interface) 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;
};

然后,你的具体实现——即策略——应该从这个接口(interface)派生:
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——即接口(interface)——而不是直接使用特定的实现,如 EthernetCommunicationSerialCommunicationCarrierPigeon 。因此,代码遵循 "program to an interface, not to an implementation" 建议。例如,您可能有一个工厂函数,如:
std::unique_ptr<Communication> CreateCommunication();

该工厂函数返回上述策略之一。可以在运行时确定返回哪种策略。
std::unique_ptr<Communication> com = CreateCommunication();
// send data regardless of a particular communication strategy
com->sendData(buffer, bufferSize);

这样,上面的代码就没有耦合到任何特定的实现,而只耦合到所有不同可能的通信策略通用的接口(interface) 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;

关于c++ - 用于处理多种通信协议(protocol)处理的设计类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61871193/

10-12 22:14