Android知识Android技术知识

程序员,你只能有一个媳妇儿!

2016-10-10  本文已影响71人  威哥爱编程

【威哥说】今天是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;

}

}

上一篇 下一篇

猜你喜欢

热点阅读