Android源码学习之单例模式应用及优点介绍

2016-02-19 10:55 4 1 收藏

给自己一点时间接受自己,爱自己,趁着下午茶的时间来学习图老师推荐的Android源码学习之单例模式应用及优点介绍,过去的都会过去,迎接崭新的开始,释放更美好的自己。

【 tulaoshi.com - 编程语言 】

单例模式定义
Ensure a class has only one instance, and provide a global point of access to it.
动态确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

    如上图所示(截取自《Head First Design Patterns》一书)。

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/bianchengyuyan/)

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/bianchengyuyan/)
通过使用private的构造函数确保了在一个应用中产生一个实例,并且是自行实例化(在Singleton中自己使用new Singleton())。
具体单例模式有什么优点呢
由于单例模式在内存中只有一个实例,减少了内存开销。
单例模式可以避免对资源的多重占用,例如一个写文件时,由于只有一个实例存在内存中,避免对同一个资源文件的同时写操作。
单例模式可以再系统设置全局的访问点,优化和共享资源访问。
其中使用到单例模式时,考虑较多的就是多线程的情况下如何防止被多线程同时创建等问题,其中《Head First Design Patterns》使用到“double-checked locking”来降低使用synchronization。
代码如下:

public class Singleton {
/* The volatile keyword ensures that multiple threads
* handle the uniqueInstance variable correctly when it
* is being initialized to the Singleton instance.
* */
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if(uniqueInstance == null) {
synchronized (Singleton.class) {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}

在Android源码中,使用到单例模式的例子很多,如:
一、 如InputMethodManager类
代码如下:

public final class InputMethodManager {
static final boolean DEBUG = false;
static final String TAG = "InputMethodManager";
static final Object mInstanceSync = new Object();
static InputMethodManager mInstance;
final IInputMethodManager mService;
final Looper mMainLooper;

创建唯一的实例static InputMethodManager mInstance;
代码如下:

/**
* Retrieve the global InputMethodManager instance, creating it if it
* doesn't already exist.
* @hide
*/
static public InputMethodManager getInstance(Context context) {
return getInstance(context.getMainLooper());
}
/**
* Internally, the input method manager can't be context-dependent, so
* we have this here for the places that need it.
* @hide
*/
static public InputMethodManager getInstance(Looper mainLooper) {
synchronized (mInstanceSync) {
if (mInstance != null) {
return mInstance;
}
IBinder b = ServiceManager.getService(Context.INPUT_METHOD_SERVICE);
IInputMethodManager service = IInputMethodManager.Stub.asInterface(b);
mInstance = new InputMethodManager(service, mainLooper);
}
return mInstance;
}

防止多线程同时创建实例
代码如下:

synchronized (mInstanceSync) {
if (mInstance != null) {
return mInstance;
}

当没有创建实例对象时,调用mInstance = new InputMethodManager(service, mainLooper);
其中类构造函数如下所示:
代码如下:

InputMethodManager(IInputMethodManager service, Looper looper) {
mService = service;
mMainLooper = looper;
mH = new H(looper);
mIInputContext = new ControlledInputConnectionWrapper(looper,
mDummyInputConnection);
if (mInstance == null) {
mInstance = this;
}
}

二、BluetoothOppManager类
代码如下:

public class BluetoothOppManager {
private static final String TAG = "BluetoothOppManager";
private static final boolean V = Constants.VERBOSE;
// 创建private static类实例
private static BluetoothOppManager INSTANCE;
/** Used when obtaining a reference to the singleton instance. */
private static Object INSTANCE_LOCK = new Object();
。。。
/**
* Get singleton instance.
*/
public static BluetoothOppManager getInstance(Context context) {
synchronized (INSTANCE_LOCK) {
if (INSTANCE == null) {
INSTANCE = new BluetoothOppManager();
}
INSTANCE.init(context);
return INSTANCE;
}
}

三、AccessibilityManager类
代码如下:

public final class AccessibilityManager {
private static final boolean DEBUG = false;
private static final String LOG_TAG = "AccessibilityManager";
/** @hide */
public static final int STATE_FLAG_ACCESSIBILITY_ENABLED = 0x00000001;
/** @hide */
public static final int STATE_FLAG_TOUCH_EXPLORATION_ENABLED = 0x00000002;
static final Object sInstanceSync = new Object();
private static AccessibilityManager sInstance;
...
/**
* Get an AccessibilityManager instance (create one if necessary).
*
* @hide
*/
public static AccessibilityManager getInstance(Context context) {
synchronized (sInstanceSync) {
if (sInstance == null) {
IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
IAccessibilityManager service = IAccessibilityManager.Stub.asInterface(iBinder);
sInstance = new AccessibilityManager(context, service);
}
}
return sInstance;
}
/**
* Create an instance.
*
* @param context A {@link Context}.
* @param service An interface to the backing service.
*
* @hide
*/
public AccessibilityManager(Context context, IAccessibilityManager service) {
mHandler = new MyHandler(context.getMainLooper());
mService = service;
try {
final int stateFlags = mService.addClient(mClient);
setState(stateFlags);
} catch (RemoteException re) {
Log.e(LOG_TAG, "AccessibilityManagerService is dead", re);
}
}

等等。。。
新年的第一周的开始,从最简单的单例模式开始记录自己的学习过程吧~~~

来源:https://www.tulaoshi.com/n/20160219/1596116.html

延伸阅读
1.MapView ,MapActivity 这种的局限在于,必须要继承MapActivity,否则无法使用MapView。纠结就在于此。但是,最新官网上已经弃用了这糟粕的MapActivity。 Version 1 of the Google Maps Android API as been officially deprecated as of December 3rd, 2012. This means that from March 3rd, 2013 you will no longer be able to request a...
标签: PHP
上一节:《PHP设计模式介绍》第三章 工厂模式 《PHP设计模式介绍》第四章 单件模式 几乎所有面向对象的程序中,总有一两个资源被创建出来,在程序应用中持续被共享使用。例如,这样的一个资源,在一个电子商务程序的数据库连接中使用:这个连接在应用程序启动时初始化,程序于是可以有效的执行;当程序结束时,这个连接最终被断开并销毁...
看到很多书中都没有对PreferenceActivity做介绍,而我正好又在项目中用到,所以就把自己的使用的在这总结一下,也方便日后查找。 PerferenceActivity是什么,看下面的截图:               Android系统截图(左)MusicPlayer Setting截图(右) 好了,我们看到Android系统本...
一次代码调试中发现一个情况,即我在查看memcached的connection时,发现总是维持在100来个左右,当然这看似没什么问题,因为memcached默认connection有1024个。但是我想的是为什么会有100来个,因为我的memcachedclient的产生采用的是单例模式我定义了一个memcachedClientFactory类,主要代码如下: 代码如下: MemcachedClientFactory{ priv...
1.需求     无论是在.net还是java平台,合理的分层架构是最普遍的模块化思路之一。     dll,jar文件无不风靡盛行,无处不在。     一天,tx团队和我说,我们现在要做android上做三个论坛的客户端,一个是新闻论坛,一个是文学论坛,一个是音乐论坛。除了数据,界面和很少的模块不一样,其他的...

经验教程

840

收藏

33
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部