Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inheritance and function selection

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading