设计模式是前人在开发过程中总结的一些经验,我们在开发过程中依据实际的情况,套用合适的设计模式,能够使程序结构更加简单。利于程序的扩展和维护。但也不是没有使用设计模式的程序就不好。如简单的程序就不用了,有种画蛇添足的感觉。
单例模式能够说是全部模式中最简单的一种,它自始至终仅仅能创建一个实例,能够有两种形式,分别为懒汉式和饿汉式
一、饿汉式。非常easy,一開始就创建了实例,实际上究竟会不会被调用也无论
package com.dzt.singleton; /** * 饿汉式。线程安全 * * @author Administrator * */ public class SingletonHungry { private static SingletonHungry instance = new SingletonHungry(); private SingletonHungry() { } public static SingletonHungry getInstance() { return instance; } }二、懒汉式,因为是线程不安全的,在多线程中处理会有问题。所以须要加同步
package com.dzt.singleton; /** * 懒汉式,这是线程不安全的,假设有多个线程在运行,有可能会创建多个实例 * * @author Administrator * */ public class SingletonIdler { private static SingletonIdler instance = null; private SingletonIdler() { } public static SingletonIdler getInstance() { if (instance == null) { instance = new SingletonIdler(); } return instance; } }加了同步之后的代码,每次进来都要推断下同步锁。比較费时。还能够进行改进
package com.dzt.singleton; /** * 懒汉式 * * @author Administrator * */ public class SingletonIdler { private static SingletonIdler instance = null; private SingletonIdler() { } public synchronized static SingletonIdler getInstance() { if (instance == null) { instance = new SingletonIdler(); } return instance; } }加同步代码块,仅仅会推断一次同步,假设已经创建了实例就不会推断,降低了时间
package com.dzt.singleton; /** * 懒汉式 * * @author Administrator * */ public class SingletonIdler { private static SingletonIdler instance = null; private SingletonIdler() { } public static SingletonIdler getInstance() { if (instance == null) { synchronized (SingletonIdler.class) { if (instance == null) instance = new SingletonIdler(); } } return instance; } }单例模式在Androidd原生应用中也有使用,如Phone中
NotificationMgr.java类
private static NotificationMgr sInstance; private NotificationMgr(PhoneApp app) { mApp = app; mContext = app; mNotificationManager = (NotificationManager) app .getSystemService(Context.NOTIFICATION_SERVICE); mStatusBarManager = (StatusBarManager) app .getSystemService(Context.STATUS_BAR_SERVICE); mPowerManager = (PowerManager) app .getSystemService(Context.POWER_SERVICE); mPhone = app.phone; // TODO: better style to use mCM.getDefaultPhone() // everywhere instead mCM = app.mCM; statusBarHelper = new StatusBarHelper(); } static NotificationMgr init(PhoneApp app) { synchronized (NotificationMgr.class) { if (sInstance == null) { sInstance = new NotificationMgr(app); // Update the notifications that need to be touched at startup. sInstance.updateNotificationsAtStartup(); } else { Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance); } return sInstance; } }