按传统j2se的写法折腾了n久都不行,终于发现了一个官方例子:
Details
An application may require one or more singleton objects to be accessed from within the application itself or by other applications. The static variable ‘_instance’, in the sample below, is initialized to null for each process running on the system. Therefore, the getInstance() method needs to check the ‘_instance’ variable each time it is invoked.
To create a singleton using the RuntimeStore, use the following sample:
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;
}
}
Use Cases
A singleton based on the above sample code might be used in the following scenarios:
- A network manager class that handles all network-related requests for an application
- A packet/message sender class
- A debugging/logging class
本文介绍了一种使用RuntimeStore实现单例模式的方法,该方法确保在整个应用程序或跨多个应用程序中只存在一个实例,并提供全局访问点。文中通过示例代码详细解释了其实现过程。

被折叠的 条评论
为什么被折叠?



