Posts

Showing posts with the label default methods

Combining State and Singleton Patterns to Create a State-Machine

Image
In my previous two posts, I discussed real-world applications for the Singleton and State design patterns. In this article, I am going to illustrate how to combine both of these patterns to create a simple wizard. Simple State Design Pattern Implementation In a typical implementation of the design pattern, State is either an interface or abstract class, with each state of the state machine being Singleton classes. My example is going to be slightly different. I will implement the state machine using a state interface and Java enums to implement the Singleton. Using an enum is the recommended way to implement a Singleton in Java. First, let's come up with a simple state interface State.java public interface State { void goNext(Context input); void goPrevious(Context input); } Now that we have an interface defined, we can derive as many states as we need. For this example, three states should be sufficient to demonstrate the wizard's functionality. Jav