首页 > 代码库 > Android 设计模式之单例模式

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;
	}
}

Android 设计模式之单例模式