英文:
Inheritance and function selection
问题
我认为我有一个常见的问题,但我不知道哪种编程模式可以解决它。
我有一个通过UDP发送数据包的类,udpSender
有一个名为sendPayload()
的函数。
我还有一个tcpSender
类,它也有一个名为sendPayload()
的函数。
最后,我有一个名为executor
的类,其中有许多函数,用于通过TCP或UDP发送字节数组以配置远程设备。它继承自udpSender
并使用来自它的executor:udpSender.sendPayload()
函数来配置其他设备。我也可以继承自tcpSender
并执行相同的操作,两者都正常工作。
但是,我如何在创建executor
对象时在UDP和TCP发送功能之间切换,而不必在构建之前更改基类?
英文:
i think i have a common probelm but i dont know which programming pattern solves it.
I have a class that sends packages via Udp. udpSender
has a a function sendPaypload()
I also have a tcpSender
class that also has a function sendPayload()
At last i have a class executor
with many many functions that configure a remote device by sending byte arrays eigther via TCP or UDP
it inherites from udpSender
and uses the executor:udpSender.sendPayload()
function from it to configure the other device.
I can also inherit from the tcpSender
and do the same and both work fine,
but how can i change between the UDP and TCP sender functionalty when i create the executor
object instead of having to change the baseclass before the build.
答案1
得分: 4
以下是翻译好的部分:
最简单的解决方法是让您的 `udpSender` 和 `tcpSender` 都实现一个具有方法 `sendPaypload()` 的接口,并将它们作为依赖项注入到您的 `executor` 类中。类似于以下内容:
interface ISender
{
void SendPayload();
}
class UdpSender : ISender {/* 实现 */}
class TcpSender : ISender {/* 实现 */}
class Executor
{
private ISender _sender;
public Executor(ISender sender) => _sender = sender;
// 其余的代码在这里
}
英文:
The simplest way to solve this is to have both your udpSender
and your tcpSender
implement an interface with the method sendPaypload()
, and inject them as a dependency to your executor
class. Something like this:
interface ISender
{
void SendPayload();
}
class UdpSender : ISender {/* implementation */}
class TcpSender : ISender {/* implementation */}
class Executor
{
private ISender _sender;
public Executor(ISender sender) => _sender = sender;
// Rest of the code goes here
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论