編輯:關於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 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;
}
}
AndroidStudio 1.4升級到1.5後,peer not authenticated錯誤
解決方法:找到項目最外層的build.gradle文件,將其中的:dependencies {classpath 'com.android.tools.build
Android中怎麼破解游戲之修改金幣數
我們在玩游戲的時候總是會遇到一些東東需要進行購買的,但是我們可能又捨不得花錢,那麼我們該怎麼辦呢?那就是用游戲外掛吧!我們這裡說的是Android中的游戲,在網上搜索一下
android開發之方形圓角listview代碼分享
先看效果圖: 首先,你得寫一個類我們命名為CornerListView[java]復制代碼 代碼如下:/** * 圓角ListView示例 * @De
Android——ListView控件
本篇介紹ListView控件,這是Android中比較重要也比較復雜的控件,這裡只談到使用ViewHolder機制優化即可。一、ListView簡介ListView是An