如何通过模式获得按价值服务?

How to get service according value with pattern?

我想根据角色价值,获得关联服务,喜欢

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

LogisticsUserDao 和 TruckOwnerDao 都实现了 UserDealService 接口。 如果role是4,driverDaoreturn,如果是5,truckOwnerDaoreturn,但是我用过

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

我不想用地图,喜欢

put(4, driverDao);

因为如果我要添加其他dao,我必须修改代码,这违反了open-closed。

那么如何解决扩展问题呢?

感谢您提前提供的所有帮助和建议。

评论里已经说了,需要工厂,但是工厂很少

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.

我会考虑工厂方法,这样您的“用户”对象就会有方法“user.createUserDealService()”,returns 需要服务。

但是我不确定这是否应该称为服务,服务是可远程调用的对象。

顺便说一句,根据用户获取 userEntity 看起来很奇怪。用户已经不是实体了吗?