1 public class DemoClass4Instance {
2 public static void main(String[] args) {
3 //TODO 单例模式,多次new创建对象的时候,只创建一份,这样做的目的:
4 //1. 类的创建过程复杂
5 //2. 类的对象消耗资源
6 User2 instance = User2.getInstance();
7 User2 instance2 = User2.getInstance();
8 System.out.println(instance == instance2); // true 证明多次创建对象,执行同一个内存地址,也就是一份
9 System.out.println(instance.equals(instance2)); //另外一种写法,也是true
10 }
11 }
12
13 class User2{
14 private static User2 user2 = null;
15
16 private User2(){
17 }
18
19 public static User2 getInstance(){
20 if(user2 == null){
21 user2 = new User2();
22 }
23 return user2;
24 }
25 }