同时初始化两个类的意义在于当两个类之间关系密切,即方法经常与另一个类进行通信时,可以简化通信。

我们直接看代码:

 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
 * 同时初始化只适用于单例模式,且不适用于饿汉式
 */
class A {
    public static A a;
    private String name = "A";

    public static A getInstance() {
        if(a==null)
        {
            a = new A();
            //初始化B
            B.getInstance();
        }
        return a;
    }

    @Override
    public String toString() {
        return name;
    }
}

class B {
    public static B b;
    private String name = "B";

    public static B getInstance() {
        if(b==null)
        {
            b = new B();
            //初始化C
            C.getInstance();
        }
        return b;
    }

    @Override
    public String toString() {
        return name;
    }
}

class C {
    public static C c;
    private String name = "C";

    public static C getInstance() {
        if(c==null)
        {
            c = new C();
            //初始化A
            A.getInstance();
        }
        return c;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class Test {
    public static void main(String[] args) {
        //未初始化
        System.out.println(A.a+" "+B.b+" "+C.c);
        //同时初始化
        A.getInstance();
        System.out.println("Hello, world!");
        System.out.println(A.a+" "+B.b+" "+C.c);
    }
}