一、饿汉式(静态常量,单线程推荐使用)
// 饿汉式(静态常量)
class Singleton01 {
// 1、构造器私有化,外部不能new
private Singleton01() {
}
// 2、本内内部创建对象实例
private static final Singleton01 instance = new Singleton01();
// 3、提供一个公共的静态方法,返回实例对象
public static Singleton01 getInstance() {
return instance;
}
}
二、饿汉式(静态代码块,单线程推荐使用)
// 饿汉式(静态代码块)
class Singleton02 {
// 1、构造器私有化,外部不能new
private Singleton02(){}
// 2、本内内部创建对象实例
private static Singleton02 instance;
static
{
// 在静态代码块中创建单例对象
instance=new Singleton02();
}
// 3、提供一个公共的静态方法,返回实例对象
public static Singleton02 getInstance()
{
return instance;
}
}
三、懒汉式(线程不安全,不推荐使用)
// 懒汉式(线程不安全)
class Singleton03 {
private Singleton03() {
}
private static Singleton03 instance = null;
public static Singleton03 getInstance() {
if (instance == null) {
instance=new Singleton03();
}
return instance;
}
}
四、懒汉式(线程安全,不推荐使用)
// 懒汉式(线程安全)
class Singleton04 {
private Singleton04() {
}
private static Singleton04 instance = null;
public static synchronized Singleton04 getInstance() {
if (instance == null) {
instance=new Singleton04();
}
return instance;
}
}
五、懒汉式(线程安全,同步代码块,不推荐使用)
// 懒汉式(线程安全,同步代码块)
class Singleton05 {
private Singleton05() {
}
private static Singleton05 instance = null;
public static synchronized Singleton05 getInstance() {
if (instance == null) {
synchronized (Singleton05.class) {
instance = new Singleton05();
}
}
return instance;
}
}
六、线程安全,双重检查,推荐使用
// 线程安全,双重检查,推荐使用
class Singleton06 {
private Singleton06() {
}
private static volatile Singleton06 instance = null;
// 提供一个静态的公有方法,加入双重检查代码,解决线程安全问题,同时解决懒加载问题
public static Singleton06 getInstance() {
if (instance == null) {
synchronized (Singleton06.class) {
if(instance == null)
{
instance = new Singleton06();
}
}
}
return instance;
}
}
七、静态内部类,推荐使用
// 静态内部内,推荐使用
class Singleton07 {
private Singleton07() {
}
private static volatile Singleton07 instance = null;
// 写一个静态内部类,该类中有一个静态属性Singleton07
private static class Singleton07Instance {
private static final Singleton07 INSTANCE = new Singleton07();
}
// 提供一个静态的公有方法,直接返回Singleton07Instance.INSTANCE
public static synchronized Singleton07 getInstance() {
return Singleton07Instance.INSTANCE;
}
}