继承和函数选择

huangapple go评论69阅读模式
英文:

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>



huangapple
  • 本文由 发表于 2023年5月17日 20:34:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272164.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定