Continuing on with the earlier discussion of simple interview questions every developer should know I describe here the singleton design pattern. Along with being able to answer the questions regarding a singleton, a developer should be able to write a class that implements the pattern.

What is a singleton?

A singleton is a design pattern that allows for only one instance of a class to be created.

Why would you use a singleton?

Singletons permit lazy initialization as well as avoiding global variables.

A simple example: Suppose that you have to load a table of state names and abbreviations into memory from a datastore that will be used by your application. You could write a static initializer in your class to retrieve the states, however it would be loaded even if you do not require the data. You could also create a class that retrieves the data from the the datastore every time someone needs it, however you realize that the data is static and will be requested many times which may impact performance.

Assuming that you are creating a web application where the states will populate a select box. The first thing you will write is a simple bean to encapsulate the data:

public class StateBean {

  private String abbreviation;
  private String name;

  public StateBean() {
    super();
  }

  public String getAbbreviation() {
    return abbreviation;
  }

  public void setAbbreviation(String abbreviation) {
    this.abbreviation = abbreviation;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

}


Next you will need to write the singleton to retrieve the data and populate a collection of StateBeans. Since you will walk through the collection using tags in a JSP page you will need to return this collection. There is a private static INSTANCE object of the same type as your singleton class. There is a private constructor, which stops it from being created outside of its own class, and there is a getInstance() method that returns the only instance. The other methods are self explanatory and will be used to get the list of states and populate the list of states.

import java.util.ArrayList;

public class StateSingleton {

  private static StateSingleton INSTANCE = null;

  private StateSingleton() {
    populateStatesList();
  }

  public static StateSingleton getInstance() {
    if (INSTANCE == null)
      INSTANCE = new StateSingleton();
    return INSTANCE;
  }

  private ArrayList statesList;

  public ArrayList getStatesList() {
    return statesList;
  }

  private ArrayList populateStatesList() {
    statesList = new ArrayList();
    // Code to retrieve states
    // Normally this would be done from a datastore
    // But we will just add some manually
    statesList.add(new StateBean("OH", "Ohio"));
    statesList.add(new StateBean("NY", "New York"));
    return statesList;
  }
}


Finally let's create a client to call the singleton:

public class StatesClient {

  public static void main(String[] args) {
    StateSingleton states = StateSingleton.getInstance();
    for (int i = 0; i < states.getStatesList().size(); i++) {
      StateBean state = (StateBean) states.getStatesList().get(i);
      System.out.println("Abbreviation: " + state.getAbbreviation()
          + ", State: " + state.getName());
    }
  }

}

0 comments: