Skip to main content

Singletons

The Singleton Pattern is a design pattern that ensures that a class has only one instance and also makes it globally accessible. This pattern lends itself very well for Subsystems on the robot (there's only one Arm, after all). For example, we need to get a reference to the Arm in Robot, Autonomouses, other subsystems. It doesn't make sense, nor is it really feasible, to pass references for every subsystem around.

To make a class a singleton in Java, we make the constructor private and add a static factory method. The constructor is private to prevent other classes from creating instances of the class. The static factory method is used to get a reference to and ensures that only one instance is ever created.

Here is an example:

public class Singleton {

// This will get initialized when the robot program is initialized
private static Singleton mInstance = new Singleton();

// `private` prevents instantiation from outside of the class.
private Singleton() {

}

// `static` allows this method to be called via Singleton.getInstance()
public static Singleton getInstance() {
return mInstance;
}

}

You can then call Singleton.getInstance() to get a reference to Singleton.