Singleton patterns in Processing

Mar 2015

To understand how to successfully implement a singleton class in Processing, you need to first understand a few lower-level mechanics of how Processing actually works.

In reality, every class in your main sketch is actually an inner class, nested inside the class named after your sketch which is extending PApplet. Due to the fact that you can’t set static inner-classes in top-level classes such as your main sketch, we’ll need to create a new java class. So, first off, create a new java file and name it appropriately; Singleton.java

Following that, it’s relatively simple to set up the singleton class in Java;

public class Singleton {

  private static Singleton instance = null;

  private Singleton() {}

  public static Singleton getInstance() {

  /*
  * Public method which is used for the singleton pattern instantiation
  * 
  * @return Singleton - Returns the singleton object.
  */

    if (instance == null) {
      instance = new Singleton();
    }

    return instance;
  }
}

Then, in Processing, you can instantiate this class easily;

Singleton s;

void setup() {
  s = Singleton.getInstance();
}
p

How can we be sure this works? Well, what happens if you try to create a second object? Well, since an instance exists, it should just return a reference to the singleton object. Let’s see this test in code;

Singleton s1;
Singleton s2;

void setup() {
  s1 = Singleton.getInstance();
  s2 = Singleton.getInstance();

  println(s1);
  println(s2);
}

To results of this test should prove that the singleton pattern has been successfully implemented. In your console you should see something like;

Singleton@125a3fa0
Singleton@125a3fa0

Where the second object is just pointing to the Singleton instantiation. Wicked.