比较好的的单例模式

  • 通过枚举类来实现单例模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
enum Single {
Single;

private () {

}

public void print(){
System.out.println("hello world");
}
}

public class SingleDemo {
public static void main(String[] args) {
Single a = Single.Single;
a.print();
}
  • 通过静态内部类来实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Singleton
{
private Singleton(){}

private static class SingletonHandler {
private static Singleton singleton = new Singleton();
}

public static Singleton getInstance(){
return SingletonHandler.singleton;
}

public void someMethod(){
System.out.println("This's display!");
}
}
  • 饿汉式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton
{
private Singleton(){}

private static Singleton singleton = new Singleton();

public static Singleton getInstance(){
return singleton;
}

public void someMethod(){
System.out.println("This's display!");
}
}