Enum Strategy pattern in Java

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

Enum Strategy pattern in Java
[Java] Strategy pattern
Reproduce Java enum in C #
Strategy pattern
Strategy Pattern
[Java] enum
Partization in Java
java callback pattern
Design pattern ~ Strategy ~
Changes in Java 11
Rock-paper-scissors in Java
[Java] Adapter pattern
Pi in Java
FizzBuzz in Java
Java pattern memo
[Java] Explanation of Strategy pattern (with sample code)
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Java Enum utilization example
My DAO pattern (Java)
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
Comments in Java source
Azure functions in java
Format XML in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
Create JSON in Java
Date manipulation in Java 8
What's new in Java 8
[Java] About enum type
Builder pattern (Effective Java)
Use PreparedStatement in Java
What's new in Java 9,10,11
Java Lambda Command Pattern
Parallel execution in Java
Initializing HashMap in Java
Java design pattern summary
Quickly implement a singleton with an enum in Java
Reverse Enum constants from strings and values in Java
Handle Enum in Mybatis TypeHandler
[Java] Change the process according to the situation with the Strategy pattern
Try using RocksDB in Java
Read binary files in Java 1
Avoid Yubaba's error in Java