Java中单例七种写法(懒汉、恶汉、静态内部类、双重检验锁、枚举)

时间:2023-04-24 22:28:48
Java中单例七种写法(懒汉、恶汉、静态内部类、双重检验锁、枚举)
/***
* 懒汉模式 1
* 可以延迟加载,但线程不安全。
* @author admin
*
*/
public class TestSinleton1 {
private static TestSinleton1 sinleton;
private TestSinleton1(){ }
public static TestSinleton1 getSinleton(){
if(sinleton==null){
return new TestSinleton1();
}
return sinleton;
}
}
/***
* 懒汉模式变种 2
* @author admin
* 使用了synchronized关键字,既可以延迟加载,又线程安全,但是执行效率低。
*/
class TestSinleton2{
private static TestSinleton2 sinleton;
private TestSinleton2(){ }
public synchronized static TestSinleton2 getSinleton(){
if(sinleton==null){
return new TestSinleton2();
}
return sinleton;
}
}
/***
* 饿汉模式 3
* @author admin
* 基于classload机制,静态变量在类装载时进行初始化
* 可以避免线程安全问题,但是没有延迟加载。
*/
class TestSinleton3{
private static TestSinleton3 sinleton = new TestSinleton3();
private TestSinleton3(){
}
public static TestSinleton3 getSinleton(){
return sinleton;
}
}
/***
* 恶汉变种模式 4
* @author admin
* 基于静态 代码块,在实例化或者第一次调用时执行
* 既可以延迟加载,又线程安全
*/
class TestSinleton4{
private static TestSinleton4 sinleton =null;
static{
sinleton = new TestSinleton4();
}
public static TestSinleton4 getSinleton(){
return sinleton;
}
}
/***
* 双重校验锁 5
* @author admin
* 懒汉模式的优化版,拥有线程安全、高效率以及延迟加载等特性。但是这种方式需要jdk1.5以上,且在一些平台和编译器下有错。
*/
class TestSinleton5{
private static volatile TestSinleton5 sinleton;
private TestSinleton5(){ }
public static TestSinleton5 getSinleton(){
if(sinleton==null){
synchronized (TestSinleton5.class) {
if(sinleton==null){ sinleton = new TestSinleton5();
}
}
}
return sinleton;
}
}
/***
* 静态内部类 6
* @author admin
* 恶汉模式的优化版,在类被装载时,静态内部类并没有被实例化,
* 只有getInstance()时才 会装载 SingletonHolder 类,静态内部类方式也能很好地,实现线程安全、高效率和延迟加载特性。
*/
class TestSinleton6{
private static class SingletonHolder {
private static final TestSinleton6 sinleton = new TestSinleton6();
}
private TestSinleton6(){}
public static final TestSinleton6 getSinleton(){
return SingletonHolder.sinleton;
} }
/***
* 枚举7
* @author admin
*避免多线程同步问题
*/
enum TestSinleton7 {
SINLETON;
}