我有一些实现接口的处理程序.每个处理程序应根据一种或多种类型为某些情况提供服务.我通过自动连线获得了这些处理程序的列表.
因此,当我想在这些迭代器上使用这些处理程序并检查其中一些是否处理该情况时,如果可以,请在该情况下运行它.
如此处所述-
@Service
public class CarCreator implments ICreator{
@Override
public boolean shouldServe(IEntity entity){
entity.getType().equal(Type.Car);
}
@Override
public boolean crate(IEntity entity){ .. some code ...}
}
@Service
public class HouseCreator implments ICreator{
@Override
public boolean shouldServe(IEntity entity){
entity.getType().equal(Type.House);
}
@Override
public boolean crate(IEntity entity){ .. some code ...}
}
@Service
public class AnimalCreator implments ICreator{
@Override
public boolean shouldServe(IEntity entity){
entity.getType().equal(Type.Animal);
}
@Override
public boolean crate(IEntity entity){ .. some code ...}
}
interface ICreator{
boolean shouldServe(IEntity entity);
public boolean crate(IEntity entity);
}
public void EntitiesCreatorManger{
List<ICreator> creators;
@Autowired
public EntitiesCreatorManger(List<ICreator> creators){ this.creators = creators;}
public void createEntities(List<IEntity> entitites){
entities.stream.forEach(entity-> {
for(ICreator creator : creators){
if(creator.shouldServe(entity){
creator.create(entity);
break;
}
}
}
}
我想以更优雅的方式做到这一点,而不是让系统中的每个接口列表都这样使用.有这种方法吗?
最佳答案
将您所有的ICreators放置在查找图中:
原文链接:https://www.f2er.com/spring/531603.htmlMap<IEntity,ICreator> map = ...
ICreator creator = map.get(entity);
if(creator != null) {
...}