单例模式

-


饿汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 饿汉式单例
*/
public class Singleton1 {
// 静态成员变量,在静态初始化时便实例化对象
private static final Singleton1 singleton = new Singleton1();
// 构造私有
private Singleton1(){
}
public static Singleton1 getSingletonInstance(){
return singleton;
}
}

懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 懒汉式单例(synchronized关键字线程安全)
*/
public class Singleton3 {
private static Singleton3 singleton;
private Singleton3(){}
// 获取实例
public static synchronized Singleton3 getSingletonInstance(){
if(singleton == null){
singleton = new Singleton3();
}
return singleton;
}
}

双重校验锁(DCL)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 双重校验锁(double-checked locking,DCL)
*/
public class Singleton4 {
/**
* 成员变量这里会加上关键字 volatile,目的是为了防止指令重排序
*/
private static volatile Singleton4 singleton;
private Singleton4(){}
// 获取实例
public static Singleton4 getSingletonInstance(){
// 第一次校验,没有实例化才进入同步代码块
if(singleton == null){
synchronized (Singleton4.class){
// 进入同步代码块后,再判断,如果为空才创建实例
if(singleton == null){
singleton = new Singleton4();
}
}
}
return singleton;
}
}

静态内部类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 静态内部类
*/
public class Singleton5 {
private Singleton5(){}

// 获取实例
public static Singleton5 getSingletonInstance(){
return SingletonHolder.SINGLETON;
}

/**
* 内部类,JVM在类加载的时候,是互斥的,可以保证线程安全
*/
private static class SingletonHolder{
private static final Singleton5 SINGLETON = new Singleton5();
}
}

枚举方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 枚举方式
*/
public enum Singleton6 {

/**
* 枚举方式实现单例
*/
SINGLETON;

public void handle() {
// to do something
}
}


Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×