Explain Singleton Instance

I am pretty new to Arduino and the programming language. I have a couple of LoRa radios talking and everything is working well, but I have some basic questions about some of the lines of code.

I am using a RadioHead Packet Radio library and this snippet of code is in there

#include <SPI.h>
#include <RH_RF95.h>

/* Feather m0 w/wing */
#define RFM95_RST     11   // "A"
#define RFM95_CS      10   // "B"
#define RFM95_INT     6    // "D"

// Change to 434.0 or other frequency, must match RX's freq!
#define RF95_FREQ 915.0

// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS, RFM95_INT);

Can someone explain exactly what that last line is doing: RH_RF95 rf95(RFM95_CS, RFM95_INT);


That line declares a static (global-scope) variable named rf95 whose type is RH_RF95. The RH_RF95 class provides a constructor that takes two parameters.

As for what, exactly, an RH_RF95 is and does and what those constructor parameters mean - you'll have to look in the documentation or source code for the library you are using.

To use this object, you will typically call methods on it: rf95.do_a_thing(). To find out what methods are exposed by this class and what they do, again: you will have to look at the documentation or the source of the library you are using.

The comment in that code is wrong. While it is creating a single instance of the class, the instance is NOT a singleton.

A singleton is an instance of a class that is designed to be instanced only once. The constructor is private. The way to create an instance of the class is to call a method, usually called Get followed by the name of the class. That method determines if the class has already been instanced. If not, it calls the constructor, and returns a pointer to the resulting instance. If the class has already been instanced, the method returns a pointer to the existing instance.

Singletons have their uses, typically where the class accesses a scarce resource such as a database, and multiple accesses are needed.

Thanks to both of you for those comments