Search code examples
javadesign-patternsrefactoringfactory-pattern

How to get service according value with pattern?


I want according to role value, to get associated service, like

LogisticsUserEntity user = this.getLogisticsUserById(userId);
UserDealService userDealService = getUserDealService(user.getRole());
UserEntity userEntity = userDealService.getUserEntity(user);

LogisticsUserDao and TruckOwnerDao both implement UserDealService interface. If role is 4, driverDao return, if it is 5, truckOwnerDao return, but I have used

@Autowired
private DriverDao driverDao;
@Autowired
private TruckOwnerDao truckOwnerDao;

I don't want to use a map, like

put(4, driverDao);

because if I want to add other dao, I have to modify the code, it violates the open-closed.

So how can I solve the extend problem?

Thanks for all your help and suggestions in advance.


Solution

  • As it was already mentioned in comments, you need a factory, but there are few factories.

    Factory - Creates objects without exposing the instantiation logic to the client and Refers to the newly created object through a common interface. Is a simplified version of Factory Method

    Factory Method - Defines an interface for creating objects, but let subclasses to decide which class to instantiate and Refers to the newly created object through a common interface.

    Abstract Factory - Offers the interface for creating a family of related objects, without explicitly specifying their classes.

    I would consider factory method, that way Your "user" object would have method "user.createUserDealService()" which returns needed service.

    Yet I'm not sure if this should be called service, services are objects that are remote callable.

    By the way it looks strange for getting userEntity based on user. Isn't user an entity already?