单例
发现博客园可以很好的设置自己的博客文章的展示,很开心,然后特此发一篇
其实这几种写法大家应该都会的,就权当拿来记录一下吧,以后复习巩固也比较方便。
这篇文章中的代码,来自一篇视频(我想找视频贴上,但我没找到,以后有机会看到再贴吧,实不好意思),上面有讲到,我觉得很好,择录了一些下来。
1.
//懒人写法|原始
//缺点:类加载的时候就初始化实例,会拖慢应用启动速度
public class PlainOldSingleton {
private static PlainOldSingleton INSTANCE = new PlainOldSingleton();
private PlainOldSingleton(){}
public static PlainOldSingleton getInstance(){
return INSTANCE;
}
}
2.
//懒加载
//缺点:不是线程安全的,有可能线程A和线程B来同时访问INSTANCE的话,会new出两个实例,如果有多个线程的话,就会new出多个实例
public class LazyNotThreadSafe{
private static LazyNotThreadSafe INSTANCE;
private LazyNotThreadSafe(){}
public static LazyNotThreadSafe getInstance(){
if(INSTANCE == null){
INSTANCE = new LazyNotThreadSafe();
}
return INSTANCE;
}
}
3.
//同步锁
//缺点:每次获取都会加锁,会有一定的性能开销
//优点:线程安全
public class LazyThreadSafeSynchronized{
private static LazyThreadSafeSynchronized INSTANCE;
private LazyThreadSafeSynchronized(){}
public static synchronized LazyThreadSafeSynchronized getInstance(){
if(INSTANCE == null){
INSTANCE = new LazyThreadSafeSynchronized();
}
return INSTANCE;
}
}
4.
//双重验证
//面试多考,volatile是java1.5之后的一个内容,要理解这个需要懂Java虚拟机
public class LazyThreadSafeDoubleCheck{
private static voltatile LazyThreadSafeDoubleCheck INSTANCE;
private LazyThreadSafeDoubleCheck(){}
public static LazyThreadSafeDoubleCheck getInstance(){
if(INSTANCE == null){
synchronized (LazyThreadSafeDoubleCheck.class){
if(INSTANCE == null){
INSTANCE = new LazyThreadSafeDoubleCheck();
}
}
}
return INSTANCE;
}
}
5.
//静态内部类
//优雅,实现了懒加载和线程安全,线程安全利用了虚拟机的机制
public class LazyThreadSafeStaticInnerClass{
private static class Holder{
private static LazyThreadSafeStaticInnerClass INSTANCE == new LazyThreadSafeStaticInnerClass();
}
private LazyThreadSafeStaticInnerClass(){}
public static LazyThreadSafeStaticInnerClass getInstance(){
return Holder.INSTANCE;
}
}