Get service that handle case from List

Viewed 50

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?

2 Answers

put all your ICreators in a lookup map:

Map<IEntity, ICreator> map = ...
ICreator creator = map.get(entity);
if(creator != null) {
...}

You seem to have an enumeration of types. Move the create logic onto the enum instances, and delegate to the create() call to the type.

public enum Type implements ICreator {
    Car {
        @Override
        public void create(IEntity entity) {
            // car creation
        }
    }, 
    House {
        @Override
        public void create(IEntity entity) {
            // house creation
        }
    }, 
    Animal{
        @Override
        public void create(IEntity entity) {
            // animal creation
        }
    };

}

public void EntitiesCreatorManager{

   public void createEntities(List<IEntity> entities){
     entities.forEach(entity -> entity.getType().create(entity));
   }

}
Related