我最近创建了一个“通信”对象/抽象类,我可以在其上使用以下函数: “发送”、“接收”、“调试发送”等
现在,我基本上想在所有其他类中使用这个对象,这样我就可以用它来发送调试消息。
目前我要做的事情:
#include "../communication/ICommunication.hpp"
extern Communication* comm;
在我想使用该对象的任何其他文件/类中。 虽然这似乎工作得很好,但我想知道是否有更简洁的方法来做到这一点。
我相信有一个软件模式可以解决这个问题,但我不记得名字和实现了。我相信,该模式的名称是一个人的姓氏。
我想知道这个模式的名称(或任何适用于此目的的模式),这样我就可以自己尝试实现。 如果可能的话,还有一些关于为什么该模式比“include and extern”代码更好的论点。
最佳答案
I'd like to know the name of this pattern (or any pattern that's good for this purpose), so I could try the implementation myself. If possible, also some arguments on why that pattern is better than the "include and extern" code.
目前使用的最佳实践是接口(interface)抽象和依赖注入(inject):
首先抽象出你将要在你的通信对象上使用的操作:
struct Communicator
{
virtual void send(const std::string&) = 0;
virtual std::string receive() = 0;
// etc
};
// injectable Communicator implementation that does nothing; this is useful as
// a default argument for code that uses communicators: it will show the dependency
// explicitly, but setting it as a default argument ensures that client code
// doesn't _have to_ use a communicator, if you don't have one available
struct NoOpCommunicator: Communicator
{
void send(const std::string&) override {}
std::string receive() override { return {}; }
} dummy_communicator; // <--- notice this global
客户端代码:
class YourClientCode // (uses a Communicator)
{
public:
YourClientCode(Communicator& c = dummy_communicator) // communicator instance,
// dependency injected here
: com(c)
{
}
private:
void f() { com.send("f()"); /* ... */ }
Communicator& com;
};
auto client1 = YourClientCode{};
auto client2 = YourClientCode{ GetActualCommunicatorReference() };
这比 include + extern 更好,因为它没有硬编码对通信器的依赖,也没有强制要求您必须启动并运行通信器才能使用客户端代码.这大大提高了代码的可测试性和可重用性。
关于C++ 在所有其他类中使用(通信)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37784050/