1

As of now I have a rest client called RestClient it implements an interface called IRestClient. Throughout my code I use IRestClient when declaring the rest clients. But several places I create the client using the new operator. So if I at some point want to change the client to NewRestClient I would have to go through my code and find all the places where I created the client.

What would be a good way to address this issue? Would a factory class like the one below be ok.

class RestClientFactory
{
    public static IRestClient create()
    {
        return new RestClient();
    }
}

Atleast that way I would only have one place to change RestClient() to NewRestClient().

user672009
  • 4,379
  • 8
  • 44
  • 77
  • 2
    [Dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) might be a solution –  Nov 02 '14 at 17:21

1 Answers1

0

A factory method pattern will only be necessary if you want/need to provide an exact implementation of IRestClient based on some arguments. Since this doesn't seem to be your case, you will be good by programming oriented to interfaces. So, instead of having this:

RestClient restClient = new RestClient();
restClient.foo("bar");

You will have this:

//declare the variable as interface
//assign the value with the class implementation
IRestClient restClient = new RestClient();
restClient.foo("bar");

So if you need a new implementation, just change the current implementationto the desired one:

IRestClient restClient = new FooRestClient();
//rest of the code remains intact
restClient.foo("bar");

If you want to move this into Factory Method Pattern, then you will have something like this:

class RestClientFactory {
    public static IRestClient defaultRestClient() {
        return new RestClient();
    }
    public static IRestClient createRestClient(String name) {
        String realName = name.toLowerCase();
        switch(realName) {
            case "foo":
                return new FooRestClient();
            case "bar":
                return new BarRestClient();
            //and on...
            default:
                return defaultRestClient();
        }
    }
}

And then you will have to initialize the instance by calling the respective method from the factory:

IRestClient restClient = RestClientFactory.createRestClient("foo");
//rest of the code remains intact
restClient.foo("bar");
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • They already have this though. I believe Q is about creation of the `RestClient` so can be swapped out by editing in one place. – weston Nov 02 '14 at 17:27
  • @weston then, as explained in my answer, there is no problem. You're just editing at a single place. If there are lot of places to change, well... that's another problem that not even the factory method can fulfill. – Luiggi Mendoza Nov 02 '14 at 17:31