/*
* 饿汉式
* 避免多线程的问题,在类被装载时就实例化对象
* */
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {
System.out.println("无法直接new对象");
}
public static Singleton getInstance() {
return singleton;
}
}
/*
* 饿汉式
* 在静态代码块中实例化对象,也是在类被装载时实例化对象
* */
public class Singleton2 {
private static Singleton2 singleton = null;
static {
singleton = new Singleton2();
}
private Singleton2() {
System.out.println("无法直接实例化对象");
}
public static Singleton2 getInstance() {
return singleton;
}
}
/*
* 懒汉式
* 线程不安全,在未前一个线程准备实例化前可能有一个线程立即进入判断
* */
public class Singleton3 {
private static Singleton3 singleton = null;
private Singleton3() {
System.out.println("无法直接实例化对象");
}
public static Singleton3 getInstance() {
if(singleton == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
singleton = new Singleton3();
}
return singleton;
}
}
/*
* 懒汉式
* 用同步锁锁定函数,线程安全
* */
public class Singleton4 {
private static Singleton4 singleton = null;
private Singleton4() {
System.out.println("无法直接实例化对象");
}
public static synchronized Singleton4 getInstance() {
if(singleton == null) {
singleton = new Singleton4();
}
return singleton;
}
}
/*
* 静态内部类,懒汉式
* 静态内部类只有第一次被使用时才被装载,也就是第一次调用getInstance时才被装载
*
*
* */
public class Singleton5 {
private static class SingletonHoler {
private static final Singleton5 singleton = new Singleton5();
}
private Singleton5() {
System.out.println("无法直接实例化对象");
}
public static final Singleton5 getInstance() {
return SingletonHoler.singleton;
}
}
/*
* 双重校验锁--jdk1.5
* */
public class Singleton6 {
private volatile static Singleton6 singleton = null;
private Singleton6() {
System.out.println("无法直接实例化对象");
}
public static Singleton6 getInstance() {
if(singleton == null) {
synchronized(Singleton6.class) {
if(singleton == null) {
singleton = new Singleton6();
}
}
}
return singleton;
}
}
设计模式-单例模式
最新推荐文章于 2024-10-06 08:57:52 发布