-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingletonTest02.java
More file actions
36 lines (31 loc) · 1.03 KB
/
Copy pathSingletonTest02.java
File metadata and controls
36 lines (31 loc) · 1.03 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
package singleton;
/**
* @author : CodeWater
* @create :2022-05-05-15:29
* @Function Description :单例模式(静态代码块)
*/
public class SingletonTest02 {
public static void main(String[] args) {
//测试
Singleton2 instance = Singleton2.getInstance();
Singleton2 instance2 = Singleton2.getInstance();
System.out.println(instance == instance2); // true
System.out.println("instance.hashCode=" + instance.hashCode());
System.out.println("instance2.hashCode=" + instance2.hashCode());
}
}
//饿汉式(静态代码块)
class Singleton2 {
//1. 构造器私有化, 防止外部能 new
private Singleton2() {
}
//2.本类内部创建对象实例
private static Singleton2 instance;
static { // 在静态代码块中,创建单例对象============================
instance = new Singleton2();
}
//3. 提供一个公有的静态方法,返回实例对象
public static Singleton2 getInstance() {
return instance;
}
}