Home > Blockchain >  Does this class comply to Factory method pattern?
Does this class comply to Factory method pattern?

Time:05-16

public class ServiceFactory {
    private static ServiceFactory instance;
    private final DishService dishService = new DishService();
    private final OrderService orderService = new OrderService();
    private  final UserService userService = new UserService();

    private ServiceFactory() {
    }

    public static synchronized ServiceFactory getInstance() {
        if (instance == null) instance = new ServiceFactory();
        return instance;
    }

    public DishService getDishService() {
        return dishService;
    }

    public OrderService getOrderService() {
        return orderService;
    }

    public UserService getUserService() {
        return userService;
    }
}

It is just a simple class for getting objects, but it seems like a messed up with naming.

If not, what should be a proper name for such a class?

CodePudding user response:

Since you are essentially accessing the same instance of a set of xxxxService instead of "constructing" new ones, it does not comply with the factory pattern.

Naming it SharedServices makes more sense, given that you made it a singleton, and that it shares various instances of services across the application.

CodePudding user response:

Factory pattern works as follows: An interface exists

public interface Foo {
  String make(String someString);
}

and there are multiple implementations of that interface:

public class DishOrder implements Foo {
  //constructor
  String make(String someString) {-- custom implementation--}
}

public class DrinkOrder implements Foo {
  //constructor
  String make(String someString) {-- custom implementation--}
}

And then the factory exists:

public class OrderFactory {
 private DishOrder dishOrder;
 private DrinkOrder drinkOrder;
 
 //constructor
 public Foo getFoo(String type) {
  if(type.equals("Dish"))
   return DishOrder;
   //and every other implementation of the interface
   //can use switch here as well
}
}
  •  Tags:  
  • java
  • Related