保证一个类仅有一个实例,并提供一个访问它的全局访问点。
核心思路: 有就返回,没有就创建。

1、饿汉

  1. public class Singleton{
  2. private static Singleton = new Singlton();
  3. private Sigleton(){}
  4. private static Singleton getInstance(){
  5. return instance;
  6. }
  7. }

2、懒汉

2.1 普通懒汉 线程不安全

  1. public class Singleton {
  2. private static Singleton instance;
  3. private Singletion(){
  4. }
  5. public static Singletion getInstance(){
  6. if (instance == null){
  7. instance = new Singleton();
  8. }
  9. return instance;
  10. }
  11. }

2.2 线程安全第一版

  1. public class Singleton{
  2. private static Singleton instance;
  3. private Singleton(){}
  4. public static synchronized Singleton(){
  5. if( instance == null){
  6. instance = new Singleton();
  7. }
  8. return instance;
  9. }
  10. }

2.3 DCL 双重校验锁

  1. public class Singleton{
  2. private static volatile Singleton instance;
  3. private Singleton(){}
  4. private static Singleton(){
  5. if( instance == null){
  6. synchronized(Singleton.class){
  7. if( instance == null){
  8. instance = new Singleton();
  9. }
  10. }
  11. }
  12. return instance;
  13. }
  14. }

2.4 枚举