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.
>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
}