单例模式是一种常用的设计模式,可以保证对象在JVM中只有一个实例存在,这样做的好处可以不用重复的创建类对象,节省一笔很大的开销,而且可以减轻GC压力。常见的创建模式有懒汉模式和饿汉模式。但是如果考虑到不同场景,设计有很大差别。
首先简单一个简单的图示例:

懒汉模式:(类加载时,不立即创建实例,所以加载类速度快,但是获取实例较慢)
-
public class SingIeton {
-
-
-
-
private static SingIeton instance = null;
-
-
-
-
private SingIeton(){
-
-
}
-
-
public static SingIeton getInstance(){
-
if(instance == null){
-
instance = new SingIeton();
-
}
-
return instance;
-
}
-
-
}
饿汉模式:(类加载时,创建实例,加载速度慢,但是获取实例快)
-
public class SingIeton {
-
-
private static SingIeton instance = new SingIeton();
-
-
-
-
private SingIeton(){
-
-
-
public static SingIeton getInstance(){
-
-
return instance;
-
}
-
-
}
如果放在多线程下,上面的写法显然是不安全的,要考虑到同步问题:
-
public class SingIeton {
-
-
-
-
private static SingIeton instance = null;
-
-
-
-
private SingIeton(){
-
-
}
-
-
-
public static synchronized SingIeton getInstance(){
-
if(instance == null){
-
instance = new SingIeton();
-
}
-
return instance;
-
-
}
-
-
}
上面的写法解决同步问题,但是有一个问题,每次调用getInstance()都要给对象加锁,这样明显效率不是最低,下面:
-
-
-
-
public class SingIeton {
-
-
-
-
private static SingIeton instance = null;
-
-
-
-
private SingIeton(){
-
-
}
-
-
public static SingIeton getInstane(){
-
if(instance == null){
-
synchronized (instance){
-
if(instance == null){
-
instance = new SingIeton();
-
}
-
}
-
}
-
return instance;
-
}
-
-
}
上面的写法在一定程度上提升了性能,但不是最优的,单例模式需要结合实际需求找到适合的解决方法,有一定的难度。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29876893/viewspace-2140450/
,如需转载,请注明出处,否则将追究法律责任。