3

I want to create Facade class to handle few operations on two services. For contacting those services I've got proxy classes.

Having abstract Proxy and derived proxy per service - how can I create this part of architecture, to avoid Resolving in Facade?

class Facade
{
    private Proxy proxy1;
    private Proxy proxy2;

    public Facade()
    {
        //I don't like this part
        proxy1 = ...Resolve<Proxy1Type>();
        proxy2 = ...Resolve<Proxy2Type>();
    }


    public void Do()
    {
        proxy1.Call();
        proxy2.Call();
    }
}

    abstract class Proxy {public void Call();}
    class Proxy1Type : Proxy {public void override Call(){}}
    class Proxy2Type : Proxy {public void override Call(){}}

What design pattern should I use to fix this case?

EDIT

Optionally I should go in this solution, but still don't like it much

class Facade
{
    private IProxy proxy1;
    private IProxy proxy2;

    //I feel it's still wrong
    public Facade(IProxy1Type p1, IProxy2Type p2)
    {
        proxy1 = p1;
        proxy2 = p2;
    }


    public void Do()
    {
        proxy1.Call();
        proxy2.Call();
    }
}
interface IProxy { void Call();}
interface IProxy1Type : IProxy{}
interface IProxy2Type : IProxy {}
class Proxy1Type : IProxy1Type { public void Call() { } }
class Proxy2Type : IProxy2Type { public void Call() { } }
Saint
  • 5,397
  • 22
  • 63
  • 107

1 Answers1

2

There are two opposite approaches and you shown them both in the question. You can either resolve dependencies inside a class using Service Locator (first sample) or inject them from the outside using Dependency Injection.

Dependency Injection (constructor injection in your case) has a few advantages:

  1. It's more clear what is needed for the Facade class to operate properly, since you do not need to dig inside the class to figure out what it'll try to resolve (and when).
  2. It's easier to unit test the Facade class, since you're able to inject test doubles via constructor; there is no need to configure a DI container in the unit tests.

You can read more about Service Locator (and why you should avoid using it) in this post.

Serhii Shushliapin
  • 2,528
  • 2
  • 15
  • 32