【剑指Offer】实现Singleton模式

题目

设计一个类,我们只能生成该类的一个实例。

不好的解法一:只适用于单线程环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton1{
private static Singleton1 instance = null;

private Singleton1(){

}

public static Singleton1 getInstance(){
if (instance == null)
instance = new Singleton1();

return instance;
}
}

不好的解法二:虽然在多线程环境中能工作但效率不高

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton2{
private static Singleton2 instance = null;

private Singleton2(){

}

public static synchronized Singleton2 getInstance(){
if (instance == null)
instance = new Singleton2();

return instance;
}
}

可行的解法:加同步锁前后两次判断实例是否已存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Singleton3{
private static Singleton3 instance = null;

private Singleton3(){

}

public static Singleton3 getInstance(){
if (instance == null){
synchronized (Singleton3.class){
if (instance == null)
instance = new Singleton3();
}
}

return instance;
}
}

强烈推荐的解法一:利用静态构造函数

1
2
3
4
5
6
7
8
9
10
11
public class Singleton4{
private static Singleton4 instance = new Singleton4();

private Singleton4(){

}

public static Singleton4 getInstance(){
return instance;
}
}

强烈推荐的解法二:实现按需创建实例

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Singleton5{
private Singleton5(){

}

public static Singleton5 getInstance(){
return Nested.instance;
}

private static class Nested{
private static Singleton5 instance = new Singleton5();
}
}