单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。这些应用都或多或少具有资源管理器的功能。每台计算机可以有若干个打印机,但只能有一个Printer Spooler,以避免两个打印作业同时输出到打印机中。每台计算机可以有若干通信端口,系统应当集中管理这些通信端口,以避免一个通信端口同时被两个请求同时调用。总之,选择单例模式就是为了避免不一致状态,避免政出多头。(此段来源与网络)
单例模式在Android源代码中使用的很广泛,在我熟悉的Telephony模块就用到了不少,比如说SIM卡的管理UiccController,电话管理CallManager等。下面看看单例模式的基本模型:
懒汉式单例:
public final class CallManager { ....... // Singleton instance private static final CallManager INSTANCE = new CallManager(); ....... /** * get singleton instance of CallManager * @return CallManager */ public static CallManager getInstance() { return INSTANCE; } ....... private CallManager() { ....... } ....... }
此例使用时直接用CallManager.getInstance()调用即可获得CallManager实例。
public class UiccController extends Handler { ...... private static UiccController[] mInstance = {null, null, null, null}; ...... public static UiccController make(Context c, CommandsInterface ci, int simId) { synchronized (mLock) { if (FeatureOption.MTK_GEMINI_SUPPORT) { if(mInstance[simId] != null) { throw new RuntimeException("UiccController.make() should only be called once"); } mInstance[simId] = new UiccController(c, ci, simId); return mInstance[simId]; } else { if (mInstance[0] != null) { throw new RuntimeException("UiccController.make() should only be called once"); } mInstance[0] = new UiccController(c, ci); return mInstance[0]; } } } ...... public static UiccController getInstance(int simId) { synchronized (mLock) { if (FeatureOption.MTK_GEMINI_SUPPORT) { if(mInstance[simId] == null) { throw new RuntimeException( "UiccController.getInstance can't be called before make()"); } return mInstance[simId]; } else { if (mInstance[0] == null) { throw new RuntimeException( "UiccController.getInstance can't be called before make()"); } return mInstance[0]; } } } ...... private UiccController(Context c, CommandsInterface ci, int simId) { ...... } ...... }
此例使用时,先UiccController.make()创建实例,然后UiccController.getInstance()获取实例。
暂时没找到例子。。。
未完待续,有不对的地方,请指正。
原文地址:http://blog.csdn.net/canghai1129/article/details/41015421