-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo1Singleton.java
More file actions
58 lines (46 loc) · 1.07 KB
/
No1Singleton.java
File metadata and controls
58 lines (46 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.wzx.sword;
/**
* @author wzx
*/
public class No1Singleton {
/**
* 锁保证线程安全的懒汉式
*/
public static class Singleton1{
volatile private static Singleton1 instance = null;
private Singleton1(){}
public static Singleton1 getInstance(){
if (null == instance) {
synchronized (Singleton1.class) {
if (null == instance) {
instance = new Singleton1();
return instance;
}
}
}
return instance;
}
}
/**
* 饿汉式
*/
public static class Singleton2{
private static final Singleton2 INSTANCE = new Singleton2();
private Singleton2(){}
public static Singleton2 getInstance(){
return INSTANCE;
}
}
/**
* 内部类保证线程安全的懒汉式
*/
public static class Singleton3{
private Singleton3(){}
public static Singleton3 getInstance(){
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder{
public static final Singleton3 INSTANCE = new Singleton3();
}
}
}