Code sample: Creating a singleton using the RuntimeStore API
The following example creates a singleton using the runtime store. In this example, the static variable _instance is initialized to null for each process running on the system, so getInstance() must check the _instance variable each time it is invoked.
For simplicity, this example does not show how to create the unique ID.
import net.rim.device.api.system.*;
class MySingleton {
private static MySingleton _instance;
private static final long GUID = 0xab4dd61c5d004c18L;
// constructor
MySingleton() {}
public static MySingleton getInstance() {
if (_instance == null) {
_instance = (MySingleton)RuntimeStore.getRuntimeStore().get(GUID);
if (_instance == null) {
MySingleton singleton = new MySingleton();
RuntimeStore.getRuntimeStore().put(GUID, singleton);
_instance = singleton;
}
}
return _instance;
}
}
Next topic: Storing data in the record store
Previous topic: Code sample: Getting a stored String from the runtime store