Calling methods of a set of interfaces with one call

So, I have the following:

public interface Client
{
    void Operation1();
    void Operation2();
}

public class Client1 : Client
{
    public void Operation1()
    {
        Console.WriteLine("Client1 - Operation1");
    }

    public void Operation2()
    {
        Console.WriteLine("Client1 - Operation2");
    }
}

public class Client2 : Client
{
    public void Operation1()
    {
        Console.WriteLine("Client2 - Operation1");
    }

    public void Operation2()
    {
        Console.WriteLine("Client2 - Operation2");
    }
}

public class Client3 : Client
{
    public void Operation1()
    {
        Console.WriteLine("Client3 - Operation1");
    }

    public void Operation2()
    {
        Console.WriteLine("Client3 - Operation2");
    }
}

      

I need a way to call a method of all clients with one call. Something like a delegate.

Basically I want to do the following: Clients.Operation1 () What are the results: Client1 - Operation1 Client2 - Operation1 Client3 - Operation1

One way to achieve this is to have the following class:

public class Clients : Client
{
    public List<Client> Clients { get; set; }
    public void Operation1()
    {
        foreach(Client c in Clients)
        {
            c.Operation1();
        }
    }
    public void Operation2()
    {
        foreach (Client c in Clients)
        {
            c.Operation2();
        }
    }
}

      

but then when I change the client interface, I also have to change the Clients class. Is there a way to generate the Clients class (or something similar) dynamically?

Please let me know if you need a better explanation because it is very difficult for me to explain this question.

+3


source to share


1 answer


You can just implement one method Execute

and pass the method you want to execute:

public class Clients
{
    public List<Client> ClientList { get; set; }

    public void Execute(Action<Client> action)
    {
        ClientList.ForEach(action);
    }

}

      

Using:



new Clients().Execute(x => x.Operation1(someString, someInt));
new Clients().Execute(x => x.Operation2());

      

In this example, you don't have to implement the interface in your class Clients

, and it doesn't have to re-do it every time the interface changes.

+5


source







All Articles