Skip to content

Singleton Pattern

Renato Dell'Osso edited this page Feb 26, 2024 · 2 revisions

Singletons are used to create classes that can only have a single instance (hence the name, singleton), such as RobotContainer or Autonomous.

We do this by having a private static variable where the type is the class we're making a singleton. For example, in Java, we do:

public class Singleton {
   private static Singleton instance;
}

Then, in our constructor, we set the instance if it is null. We throw an exception if it is not null.
public class Singleton {
   private static Singleton instance;

   public Singleton() {
       if (instance != null) {
           // Throw an exception or do some logging
           return;
       }

       instance = this;
   }
}

So why use a singleton?

To stop our future selves from making dumb choices. Many classes, such as RobotContainer should not have multiple instances. We only have one robot, so we only want a single container for that robot. Multiple containers would mean multiple subsystems and thus multiple motors on the same port and then issues. So, we make RobotContainer a singleton!

image
-Brought to you by Dr. Singleton

Clone this wiki locally