为上述功能创建通用 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;