If my class has many children, how can I initialize an object that is a random child of my class?

Viewed 136

For example.

Parent: Vehicle Children: Car, Train, Horse

I want to do the following

Vehicle randVehicle = new RandomeVehicleChildObject;

I was thinking I could do this:

Vehicle randVehicle;
Random r = new Random();
int x = r.nextInt();

if(x == someInt)
   randVehicle = new Car();
else if(x == otherNum)
   randVehicle = new Train();
else
   randVehicle = new Horse();

However, what if my class has many more children? Like 15 or 20? I feel like writing so many if-else chains or switches would be a pain. Is there a way to just do it in one line?

1 Answers

I'd recommend something like the following:

class VehicleFactory {
    private final List<Supplier<Vehicle>> constructors = new ArrayList<>();

    public void addConstructors(Supplier<Vehicle>... constructors) {
        this.constructors.addAll(Arrays.asList(constructors));
    }

    public Vehicle make() {
        return constructors.get(random.nextInt(constructors.size()).get();
    }
}

Then when you want to start making vehicles:

VehicleFactory factory = new VehicleFactor();
factory.addConstructora(Car::new, Horse::new, Bike::new);
Vehicle randomVehicle = factory.make();
Related