在blakcberry实现单态

来源:互联网 发布:音量放大软件中文版 编辑:程序博客网 时间:2024/05/29 07:14

按传统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
原创粉丝点击