Characteristics of the single-case mode:
1. Only one instance of a class
2. Create this instance yourself
3, the entire system to use this example
The form of a singleton pattern:
1, a Hungry man type single case
publicclassSingleton {
privateSingleton(){}
//在自己内部定义自己一个实例,是不是很奇怪?
//注意这是private 只供内部调用
privatestatic Singleton instance = newSingleton();
//这里提供了一个供外部访问本class的静态方法,可以直接访问
publicstaticSingleton getInstance() {
returninstance;
}
}
2、懒汉式单例类
privatestaticSingleton instance = null;
publicstaticsynchronized Singleton getInstance() {
//这个方法比上面有所改进,不用每次都进行生成对象,只是第一次
//使用时生成实例,提高了效率!
if(instance==null)
instance=newSingleton();
returninstance; }
}
The second form is the lazy initialization, that is, the first call when the initial singleton, and then no longer generated.
Note that synchronized in the form of lazy initialization, this synchronized is important, if there is no synchronized, then using getinstance () is possible to get multiple singleton instances.
Generally the first is more secure
3, the more commonly used are:
publicclassSingleton {
privatevolatile staticSingleton singleton;
privateSingleton(){}
publicstaticSingleton getInstance(){
if(singleton==null){
synchronized(Singleton.class){
if(singleton==null){
singleton=newSingleton();
}
}
还可以参考一下android的Activity加载模式:
1、singleTop
2、singleTask
3、singleInstance
Android Single-instance mode