Android常见设计模式—单例模式
2020-03-12 本文已影响0人
大漠孤烟直_v
作用:保证应用程序中,一个类只有一个实例存在。
好处:
单例模式在内存中只有一个实例,减少了内存开销
可以避免对资源的多重占用,例如写一个文件时,由于只有一个实例在内存中,避免对同一个资源文件的同时操作
第一种:(懒汉式)
public class Singleton {
private Context mContext;
/**
* 持有私有静态实例,防止被访问
* 此处赋值为null 目的是实现延迟加载
*/
private static Singleton singleton = null;
/**
* context.getApplicationContext(); 将单例的的上下文置于application的上下文,防止内存泄漏
*/
private Singleton(Context context) {
mContext = context.getApplicationContext();
}
private Singleton getSingleton(Context context) {
if (singleton != null) {
singleton = new Singleton(context);
}
return singleton;
}
}
这种有个问题,不同步,在对数据库对象进行频繁的读写操作时,不同步问题就大了。
第二种:
/**
*同步代方法
*/
private synchronized Singleton getSingleton(Context context) {
if (singleton != null) {
singleton = new Singleton(context);
}
return singleton;
}
或者
/**
*同步代码块
*/
private Singleton getSingleton(Context context) {
synchronized (Singleton.class) {
if (singleton != null) {
singleton = new Singleton(context);
}
}
return singleton;
}
Android中常见的单例模式有:InputMethodManager
、BluetoothOppManager
、CalendarDatabaseHelper
注意:Application并不是单例模式
在Application
源码中,我们可以知道它的构造方法是公有的,意为着可以生出多个Application
实例,那为什么Application
能实现一个app只存在一个实例的呢?我们再去看Application
的父类ContextWrapper
的源码可以知道,就算有多个Applicaiton
实例,但是没有通过attach()
绑定相关信息,没有上下文环境,就三个字,然并卵。