1)饿汉模式
此方法利用的Java的两个特性,
第一个特性:私有的构造函数,保证了此类的对象只能在类内创建,类外不可以对此类new
第二个特性:静态属性且有赋值时候,在类Singleton加载时instance 完成了初始化,当被调用时 ,已经是被创建
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){
}
public static Singleton getInstance() {
return instance;
}
}
2)懒汉模式
此模式又可以分为三种方法
第一种方法:类同步方法锁,在多线程中同时只能有一个线程调用返回实例的方法,其他线程等待锁释放了才能被调用,所以保证了其他线程调用时,实例已经被创建
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
第二种方法:类同步块锁,对类上锁,多线程中同时也只有一个线程可以执行同步块内的方法,其他线程等
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance2() {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
return instance;
}
}
第三种方法:双检测锁机制,首先检测实例有没有被创建,如果没有则对类进行上锁创建实例对象,防止同步块有排队获取锁,然后对实例进行二次判断,
这样防止了实例再次创建。
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance3() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
3)静态内置类实现
此方法和懒汉式还是有点差别,懒汉式是类进行加载时就实例化了对象,而内部静态类是当内部类进行加载时instance才被实例化,才实例化了对象
public class Singleton {
private Singleton() {
}
private static class SingletonHandler {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHandler.instance;
}
}
4)枚举类实现
枚举类在使用时,构造方法会被自动调用,根据这个特性可以实现单例模式
public class Singleton {
private Singleton(){
}
public static Singleton getInstance() {
return EnumSingleton.SINGLETON.getInstance();
}
private enum EnumSingleton {
SINGLETON;
private Singleton instance;
private EnumSingleton() {
instance = new Singleton();
}
public Singleton getInstance() {
return instance;
}
}
}
5)静态块实现
此方法主要是利用静态块在类加载时会执行这个特性
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton(){
}
public static Singleton getInstance() {
return instance;
}
}