Skip to content

singletons

tekdemo edited this page Oct 4, 2024 · 1 revision

Singletons

The Singleton pattern is designed to allow one, and only one occourance of a class; This means that Static functions can safely interact with the one instance without particular worry.

This example sensor system is a typical use case for our robot designs.

public ExampleSensorSystem{
    static ExampleSensorSystem instance;
    private Ultrasonic sensor = new Ultrasonic(0,1);

    private ExampleSensorSystem(){} //note private constructor
    public static ExampleSensorSystem getInstance(){
        //Check to see if we have an instance; If not, create it. 
        if(instance==null) instance = new ExampleSensorSystem();
        //If so, return it. 
        return instance
    }
    public double getDistance(){
        return sensor.getRangeInches();
    }
    public static double GetDistanceStatic(){
        return getInstance().getRangeInches();
    }
}

Elsewhere, these are all valid ways to interface with this sensor, and get the data we need

ExampleSensorSystem.getInstance().getDistance(); //member/instance access
ExampleSensorSystem.GetDistanceStatic(); //static access

var sensor = ExampleSensorSystem.getInstance();
// do other things
sensor.getDistance(); //static access

In most cases, you'll want to pick and choose only one type of pattern to avoid confusion. Member access is more typical of this class pattern, since you can simply save the reference as shown in the example.

Clone this wiki locally