The Wizard Design Pattern

We all love wizards…. (Software wizards I mean). We are always happy to jump on those ”Next” buttons like we were dancing the funky chicken on our… well you get the point. So today we bring you your beloved wizard into your coding experience. Let’s jump right into an example.

Say you want to design a ConservativePerson class.

import java.util.List; 
class ConservativePerson{ 
  
    private boolean isVirgin; 
    private boolean isMarried; 
    private List<string> children; 
  
    ConservativePerson(boolean virgin, boolean married, List<string> children) { 
        this.isVirgin = virgin; 
        this.isMarried = married; 
        this.children = children; 
    } 
  
    public boolean isVirgin() { 
        return isVirgin; 
    } 
    public boolean isMarried() { 
        return isMarried; 
    } 
  
    public List<string> getChildren() { 
        return children; 
    } 
} 

As such it has some constrains.

  • He must be married before he can be… well, not a virgin.
  • He can’t be a virgin before he can have children (as far as we know).

In the old days, which is basically all days until today…, you would probably define all kinds of modifiers methods for this class which will throw an exception in case of invariant invalidation such as NotMarriedException and VirginException. Not anymore.

Today we will do it by using the Wizard Design Pattern. We use a fluent interface style and utilize the power of a modern IDE to create a wizard-like feeling when building a ConservativePerson object. We know, we know, stop talking and show us the code… but before we will present the wizard code we will show you it usage so you will get a grasp of what we are talking about…

public class Main { 
public static void main(String[] args) { 
    ConservativePersonWizardBuilder wizard = new ConservativePersonWizardBuilder(); 
    ConservativePerson singlePerson = wizard. 
            createConservativePerson(). 
            whichIsSingle(). 
            getObject(); 
    ConservativePerson familyManPerson = wizard. 
            createConservativePerson(). 
            whichIsMarried(). 
            andNotVirgin(). 
            andHasChildNamed("Noa"). 
            anotherChildNamed("Guy"). 
            lastChildName("Alon"). 
            getObject(); 
  } 
  
} 

Now, it may look just like an ordinarily fluent interface, but the cool thing here is that a method is available for calling only if the current object state allows it. This means you will not be able to call the method andNotVirgin if you haven’t called the method whichIsMarried.
See the following set of screen shots:

and after we state he is married we can:

Here is the wizard code. I urge you to copy/paste it to your IDE and give it a try by building an object with it.

import java.util.ArrayList; 
  import java.util.List; 
   
   public class ConservativePersonWizardBuilder { 
     private boolean isVirgin; 
     private boolean isMarried; 
     private List<String> children = new ArrayList<String>(); 
       
     public SetMarriedStep createConservativePerson(){ 
         return new SetMarriedStep(); 
     } 
   
     class SetMarriedStep { 
        public SetVirginStep whichIsMarried(){ 
             isMarried = true; 
             return new SetVirginStep(); 
         } 
    
         public FinalStep whichIsSingle(){ 
             isMarried = false; 
             return new FinalStep(); 
         } 
     } 
  
     class SetVirginStep { 
         public AddChildrenStep andNotVirgin(){ 
             isVirgin = false; 
             return new AddChildrenStep(); 
         } 
         public FinalStep butStillAVirgin(){ 
             isVirgin = true; 
             return new FinalStep(); 
         } 
     } 
  
     class FinalStep { 
         public ConservativePerson getObject(){ 
             return new ConservativePerson(isVirgin, isMarried, children); 
         } 
     } 
  
     class AddChildrenStep { 
         public AddChildrenStep andHasChildNamed(String childName) { 
             children.add(childName); 
             return new AddChildrenStep(); 
         } 
         public AddChildrenStep anotherChildNamed(String childName) { 
             children.add(childName); 
             return new AddChildrenStep(); 
         } 
         public FinalStep lastChildName(String childName){ 
             children.add(childName); 
             return new FinalStep(); 
         } 
     } 
 } 

As you can see the wizard consists of several steps. Each step is represented by a dedicated inner class. Each step reveals the legal available operations by its methods. Each method will then return a new step according to the change it has made. This way an attempt to create an illegal object will be detected at compile time instead of runtime.

This pattern is actually being used in our production code. One example that comes to mind is the MediaJob class. This class describes a manipulation on some media files. In order to submit a job to the system, one has to create a MediaJob object. The problem is that this object has many parameters that could be assigned with contradicting values that create an illegal object state. By using the Wizard pattern, one can easily build a legal job without the need to know the entire (and complicated…) set of constrains.

That is all for now. Hope you’ll give it a try….. We plan to write a more formal description of it (GOF style) in the near future.

References:  The Wizard Design Pattern  from our JCG partner Nadav Azaria & Roi Gamliel at the DeveloperLife

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

2 Responses to "The Wizard Design Pattern"

  1. niklasplessing says:

    how about this pattern im comparison. seems much more convenient…
    http://refactormycode.com/codes/194-fluent-builder

  2. Jan Stadler says:

    Very nice, thx

Leave a Reply


7 × = twenty eight



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close