Aks
Aks

Reputation: 184

Is it good design to use factory pattern for creating Services?

I have read about Factory Pattern where it is used to create Objects on the fly based on some conditions. However, is it a norm to create Service classes based on those conditions.

class ServiceFactory { 

    DummService1 A;
    DummService2 B;
    DummService3 C;

    Service getService(String condition) {

      switch condition:
          case A:
             return new A()
          case B:
             return new B()
          case C:
             return new C()
    }
}

class DummyService1 implements Service{}
class DummyService2 implements Service{}
class DummyService3 implements Service{} 

Above is an example. Also, I am trying to do this in Spring, so these service classes are Autowired (did not want to complicate the above example with Spring Specific syntax).

Upvotes: 2

Views: 218

Answers (1)

René Link
René Link

Reputation: 51413

is it a norm to create Service classes based on those conditions.

It is one way of creating services. Another might be to use an SPI and the ServiceLoader. But then you might introduce a method in the service itself to find out if it is suitable. E.g.

public Service {
    public boolean isSuitable(String condition);

    // ... Service methods
}

you might then lookup the correct service in this way

Service suitableService = null;

for(Service serviceCandidate : ServiceLoader.load(Service.class)){
   if(serviceCandidate.isSuitable(condition)){
        suitableService = serviceCandidate;
        break;
   }
}

In Java 8 you might replace the switch with a map of method references:

private Map<String, Supplier<Service>> services = new HashMap<>();

public ServiceFactory() {
    services.put("A", A::new);
    services.put("B", B::new);
    services.put("C", C::new);
}

Service getService(String condition) {
    Supplier<Service> supplier = services.get(condition);
    if(supplier != null) {
        return supplier.get();
    }
    return null;
}

Also, I am trying to do this in Spring, so these service classes are Autowired

When you do this in spring you usually use @Qualifier instead of condition.

@Autowired
@Qualifier("A")
private Service service;

Upvotes: 2

Related Questions