1、饿汉式-静态变量
/**
* 单例模式-饿汉式-静态变量
*/
public class Singleton {
//创建静态变量,类加载时,就会进行初始化
private static Singleton singleton = new Singleton();
//构造器私有
private Singleton() {
}
//提供一个获取实例的接口
public static Singleton getSingleton() {
return singleton;
}
}
2、饿汉式-静态代码块
/**
* 单例模式-饿汉式-静态代码块
*/
public class Singleton {
//定义一个静态变量
private static Singleton singleton;
//通过static进行初始化
static {
singleton = new Singleton();
}
//构造器私有
private Singleton() {
}
//返回实例
public static Singleton getSingleton() {
return singleton;
}
}
3、懒汉式-线程不安全
/**
* 单例模式-懒汉式-线程不安全
*/
public class Singleton {
private static Singleton singleton;
//构造器私有
private Singleton() {
}
//提供一个获取实例的方法
public static Singleton getSingleton() {
//判断实例是否为空,如果为空进行初始化
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
4、懒汉式-方法加锁
/**
* 单例模式-懒汉式-方法加锁
*/
public class Singleton {
//定义静态变量
private static Singleton singleton;
//构造器私有
private Singleton() {
}
//对方法加锁,保证同一时间之后一个线程,能够进入该方法
public static synchronized Singleton getSingleton() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
5、懒汉式-双重检查
/**
* 单例模式-懒汉式-双重检查-推荐
*/
public class Singleton {
//静态变量
private static Singleton singleton;
//构造器私有
private Singleton() {
}
//获取实例的方法
public static Singleton getSingleton() {
//第一层判断是否为空
if (singleton == null) {
//加入锁
synchronized (Singleton.class) {
//再次判断是否为空,如果为空,进行实例化
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
6、静态内部类
/**
* 单例模式-懒汉式-静态内部类-推荐
*/
public class Singleton {
//静态内部类,当类加载的时候,不会进行初始化,静态内部类,当调用的时候才会记在
private static class SingletonHolder {
private static final Singleton SINGLETON = new Singleton();
}
//返回实例
public static Singleton getInstance() {
return SingletonHolder.SINGLETON;
}
//构造器私有
private Singleton() {
}
}
7、枚举
/**
* 单例模式-枚举
*/
public enum Singleton {
SINGLETON;
public static Singleton getSingleton() {
return SINGLETON;
}
}