static单例设计模式
# static 单例设计模式
利用 static 让类只能 "new" 一次?
public class Earth {
private static Earth earthInstance = new Earth();
private Earth() {
}
public static Earth getEarthInstance() {
return earthInstance;
}
public void hello() {
System.out.println("Hello");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
run:
public class Test {
public static void main(String[] args) {
// Earth earth = new Earth(); --->(x)
Earth earthInstance = Earth.getEarthInstance();
earthInstance.hello(); // Hello
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
编辑 (opens new window)
上次更新: 2022/09/26, 16:55:15