Fork me on GitHub

单例模式

1、饿汉单例模式(线程安全)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  public class object{

private static final object obj = new object();

public object(){

}

public static object getInstance(){

return obj;

}
}

2、懒汉式单例(线程不安全,除非加上同步关键字)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
   public class Singleton{

private static Singleton instance ;

private Singleton(){

}

public static synchronized Singleton getInstance(){

if(instance == null){

instance = new Singleton();
}

return instance;
}
}

3、Double Check Lock(DCL)实现单例

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
 public class Singleton{

private static Singleton instance = null;

private Singleton(){

}

public static Singleton getInstance(){

if(instance == null){

synchronized(Singleton.class){

if(instance == null){

instance = new Singleton();

}
}
}

return instance;

}
}

4、静态内部类单例模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   public class Singleton{

private Singleton(){

}

private static class SingletonHolder{

private static final Singleton instance = new Singleton();

}

public static Singleton getInstance(){

return SingletonHolder.instance;

}

}

5、枚举单例

public enum SingletonEnum{
       INSTANCE;
       public void doSomething(){



       }

}