Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u014619545/article/details/90287561
Android common design pattern - singleton
1. hungry Chinese-style
// Only the inner class as static.
public class SingIn{
//在自己内部定义自己的一个实例,只供内部调用
private static final SingIn instance = new SingIn();
private SingIn(){
}
}
// here it provides a static method for external access to this class, you can directly access
public static SingIn getInstance(){
return instance;
}
2. lazy style
private volatile static Singleton mSingleton = null;
private Singleton () {}
public static Singleton getInstance() {
if (mSingleton == null) {
synchronized (Singleton.class) {
if (mSingleton == null) {
mSingleton = new Singleton();
}
}
}
return mSingleton;
}