mercredi 20 juillet 2016

Composite design pattern: how to pass results from one component into another?

I have the following code:

interface IService
{
    void Execute();
}

class ServiceA : IService
{
    public void Execute() { ... }
}

class ServiceB : IService
{
    public void Execute() { ... }
}

class ServiceComposite : IService
{
    List<IService> _services = new List<IService>();

    public ServiceComposite()
    {
        _services.Add(new ServiceA());
        _services.Add(new ServiceB());
    }

    public void Execute()
    {
        foreach (IService service in _services)
        {
            service.Execute();
        }
    }
}

The problem is that ServiceB depends on some results from ServiceA. My idea is to create container class for storing the results, then inject it into both ServiceA and ServiceB:

class ServiceResults
{
    public string SomeProperty {get; set;}
}

public ServiceComposite()
{
    ServiceResults result = new ServiceResults();
    _services.Add(new ServiceA(result));
    _services.Add(new ServiceB(result));
}

I am wondering if it is the best possible way to solve the problem. Maybe it breaks some principles or rules of which I don't know, or is simply "code smell". What are the better ways to do this?

Aucun commentaire:

Enregistrer un commentaire