When creating an object, I think that the code may be refreshed if you use enum instead of conditional branching using if statement or switch statement.
The following is an implementation example of Enum that returns the corresponding animal when a bark is input.
AnimalCreator.java
public enum AnimalCreator {
CAT("nyaa", Cat::new),
DOG("waon", Dog::new),
BIRD("pii", Bird::new);
private String nakigoe;
private Supplier<Animal> create;
AnimalCreator(String nakigoe, Supplier<Animal> creator) {
this.nakigoe = nakigoe;
this.create = creator;
}
//Map that reverses Animal from the bark
private static final Map<String, AnimalCreator> map =
Stream.of(AnimalCreator.values())
.collect(Collectors.toMap(a -> a.nakigoe, a -> a));
//factory method
public static Animal of(String nakigoe) {
return Optional.ofNullable(map.get(nakigoe))
.map(a -> a.create.get())
.orElseThrow(IllegalArgumentException::new);
}
}
The caller looks like this. There are no conditional branches, so the code is cleaner.
main.java
Animal cat = AnimalCreator.of("nyaa");
Animal dog = AnimalCreator.of("waon");
Animal bird = AnimalCreator.of("pii");
Animal mouse = AnimalCreator.of("chu");
// java.lang.IllegalArgumentException occurs
Recommended Posts