Code Labs

Plain Java

State Design Pattern: Using Java Enums

If you want to use a Java Enum as State pattern implementation you have at least two options where to write your state transition logic. In the first case you can put it directly into your Enum source file. This is advisable for less complex and simple logic. If your logic is more complex you should use one separate class for each state.

See the following examples for both possible approaches. The class Lightis used as state context. By the way, using Java Enums is a good choice if you want to store the object state as field of a JPA entity.