【威哥說】今天是10月10日了,上班第3天,大家應該已經調整好狀態了吧!既然選擇了前方便風雨兼程,不要有一絲的松懈。將來的你一定會感謝現在努力拼命的自己。【也許你的朋友正在等你轉發到朋友圈】
【正文】
設計模式是前人在開發過程中總結的一些經驗,我們在開發過程中根據實際的情況,套用合適的設計模式,可以使程序結構更加簡單,利于程序的擴展和維護,但也不是沒有使用設計模式的程序就不好,如簡單的程序就不用了,有種畫蛇添足的感覺。
單例模式可以說是所有模式中最簡單的一種,它自始至終只能創建一個實例,可以有兩種形式,分別為懶漢式和餓漢式。
餓漢式,很簡單,一開始就創建了實例,實際上到底會不會被調用也不管
/**
* 餓漢式,線程安全
*
* @author 才子
*
*/
public class SingletonHungry {
private static SingletonHungry instance = new SingletonHungry();
private SingletonHungry() {
}
public static SingletonHungry getInstance() {
return instance;
}
}
懶漢式,由于是線程不安全的,在多線程中處理會有問題,所以需要加同步
/**
* 懶漢式,這是線程不安全的,如果有多個線程在執行,有可能會創建多個實例
*
* @author 才子
*
*/
public class SingletonIdler {
private static SingletonIdler instance = null;
private SingletonIdler() {
}
public static SingletonIdler getInstance() {
if (instance == null) {
instance = new SingletonIdler();
}
return instance;
}
}
加了同步之后的代碼,每次進來都要判斷下同步鎖,比較費時,還可以進行改進
/**
* 懶漢式
*
* @author 才子
*
*/
public class SingletonIdler {
private static SingletonIdler instance = null;
private SingletonIdler() {
}
public synchronized static SingletonIdler getInstance() {
if (instance == null) {
instance = new SingletonIdler();
}
return instance;
}
}
加同步代碼塊,只會判斷一次同步,如果已經創建了實例就不會判斷,減少了時間
/**
* 懶漢式
*
* @author 才子
*
*/
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;
}
}