单例类全局唯一,无论是哪个方法调用单例类,它的实例化就只是那一个,不会改变
以下为几种单例模式:
1、懒汉(非线程安全)
/***
* 懒汉,非线程安全
*/
public class SingletoneTest {
private static SingletoneTest instance;
private SingletoneTest() {
}
public static SingletoneTest getInstance() {
if (instance == null) {
instance = new SingletoneTest();
}
return instance;
}
}
2、懒汉,线程安全
/***
* 懒汉,线程安全
*/
public class SingletoneTest {
private static SingletoneTest instance;
private SingletoneTest(){}
public static synchronized SingletoneTest getInstance(){
if(instance == null){
instance = new SingletoneTest();
}
return instance;
}
}
这种线程安全的懒加载有一个问题,就是如果我没有实例化,进入synchronized方法中是没有问题,但是如果我已经实例化了,仍然是要进入synchronized方法中,这样的性能有点问题
3、懒汉,线程安全,变种
/***
* 懒汉,线程安全,变种
*/
public class SingletoneTest {
private static SingletoneTest instance;
private SingletoneTest(){}
public static SingletoneTest getInstance(){
if(instance == null){
synchronized (instance){
if (instance == null){
instance = new SingletoneTest();
}
}
}
return instance;
}
}
4、饿汉
/***
* 饿汉
*/
public class SingletoneTest {
private static SingletoneTest instance = new SingletoneTest();
private SingletoneTest(){}
public static SingletoneTest getInstance(){
return instance;
}
}
5、饿汉变种
/***
* 饿汉,变种
*/
public class SingletoneTest {
private static SingletoneTest instance = null;
static {
instance = new SingletoneTest();
}
private SingletoneTest(){}
public static SingletoneTest getInstance(){
return instance;
}
}
这种和一般的饿汉模式看起来挺像,但是其实都是一样的,都是在初始化的时候就将对象实例化了
6、使用静态内部类
/***
* 使用静态内部类
*/
public class SingletoneTest {
private static class SingletoneHoder{
private static final SingletoneTest instance = new SingletoneTest();
};
private SingletoneTest(){}
public static final SingletoneTest getInstance(){
return SingletoneHoder.instance;
}
}