Loose connection of static material

I have a class ClassAthat uses a client that I wrote to send text messages TextClient, to send text messages through a call to the static method

TextClient.Send(string text, string destination)
// where destination is a phone number

However, I also have an email client class MailClientthat sends letters with the same signature:

MailClient.Send(string text, string destination)
// where destination is an email address

I would like to β€œenter” which of these clients should be used - is this possible?

(Note. I know about the problems that can arise when there are completely different rules for which values destinationcan be held and considered valid, but the values ​​are retrieved from another place, so this class is not needed that I want to divert this in the first place.)

+3
source share
5 answers

In principle, get rid of static methods. Create an interface ( IMessageClient), and then two implementations ( TextClientand MailClient) using the instance methods that implement the interface. Then you can easily paste the appropriate IMessageClientinto the rest of the application.

You can of course use delegates to avoid creating an interface here, but I will definitely move on to using interfaces:

  • Names (interface name, method name, and parameter names) convey information when you use them.
  • It allows you to use multiple methods in one interface.
  • , ,
+7

, , .

public interface IMessageClient
{
    public void Send(string text, string destination);
}

public class TextClient : IMessageClient
{
    public void Send(string text, string destination)
    {
        // send text message
    }
}

public class MailClient : IMessageClient
{
    public void Send(string text, string destination)
    {
        // send email
    }
}

public class ClassA
{
    private IMessageClient client;

    public ClassA(IMessageClient client)
    {
        this.client = client;
    }
}

, , , .

+4

, , .

TextClient MailClient, singleton , . IMessageSender (. ) , .

public interface IMessageSender
{
    void Send( string message, string destination );
}

public class TextClient : IMessageSender { ... }
public class MailClient : IMessageSender { ... }

( ), , :

class SomeConsumer
{
    private Action<string,string> m_SendDelegate;
    public SomeConsumer( Action<string,string> sendDelegate ) 
    { 
        m_SendDelegate = sendDelegate;
    } 

    public DoSomething()
    {
        // uses the supplied delegate to send the message
        m_SendDelegate( "Text to be sent", "destination" ); 
    }
}

var consumerA = new SomeConsumer( TextClient.Send ); // sends text messages
var consumerB = new SomeConsumer( MailClient.Send ); // will send emails
+2

static, Send() TextClient MailClient. .

, .

+1

.

public interface ISender
{
void Send(string text, string destination);
}

, , .

0

Source: https://habr.com/ru/post/1754614/


All Articles