I have some handlers who implements interface. Each handler should serve some cases according to one or more types. I get the list of that handlers via autowired. So when I want to use these handler in the iterate over them and check whether some of them handle the case, if so I run it on the case. As describe here -
@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;
}
}
}
}
I want to do it with more elegant way and not for each list of interfaces in my system to use like this. Is there such way?