Android 設計模式之單例模式
設計模式是前人在開發過程中總結的一些經驗,我們在開發過程中根據實際的情況,套用合適的設計模式,可以使程式結構更加簡單,利於程式的擴充和維護,但也不是沒有使用設計模式的程式就不好,如簡單的程式就不用了,有種畫蛇添足的感覺。
單例模式可以說是所有模式中最簡單的一種,它自始至終只能建立一個執行個體,可以有兩種形式,分別為懶漢式和餓漢式
一、餓漢式,很簡單,一開始就建立了執行個體,實際上到底會不會被調用也不管
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 insteadmCM = 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;}}