Showing posts from April, 2017

Using a State-Machine to Control a Wizard

On previous articles, I wrote about real-world usages for the State and Singleton design patterns. I also wrote about using these two patterns together to create a state-machine. Now, I am going use that state-machine to control a Wizard. I am going to use Java Swing to create the User Interface classes. To create my interface using Java Swing, I am going to create three panels for contents, one panel to provide the navigation controls, and a frame to hold it all together. It will be a simple example, but one you could easily expand should you have the need to create your own wizard. The Frame The frame is the application window. I will not go to much into details about the Java JFrame class, as I assume you have some basic knowledge of Java and Java Swing. If you don't much about Java Swing, I suggest you visit this Oracle tutorial on how to create frames. public class Main extends JFrame { private CardsPanel cards = new CardsPanel(); private NavigationPanel but…

Combining State and Singleton Patterns to Create a State-Machine

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 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. Java allows enum …