设计模式之单例模式

单例模式
有且只有一个对象,且对象自身构造出来。

1.懒汉

点击查看代码
public class Singleton01 {
  private static final Singleton01 INSTANCE = new Singleton01();

  private Singleton01() {}

  public static Singleton01 getInstance() {
    return INSTANCE;
  }
}

或者

public class Singleton01 {
  private static Singleton01 INSTANCE = null;

  static {
    INSTANCE = new Singleton01();
  }

  private Singleton01() {}

  public static Singleton01 getInstance() {
    return INSTANCE;
  }
}

2

点击查看代码
public class Singleton02 {
  private static Singleton02 INSTANCE = null;

  private Singleton02() {}

  public static synchronized Singleton02 getInstance() {
    if (INSTANCE == null) {
      INSTANCE = new Singleton02();
    }
    return INSTANCE;
  }
}

3

点击查看代码
public class Singleton03 {
  private static Singleton03 INSTANCE = null;

  private Singleton03() {}

  public static Singleton03 getInstance() {
    if (INSTANCE == null) {
      synchronized (Singleton03.class) {
        INSTANCE = new Singleton03();
      }
    }
    return INSTANCE;
  }
}
出现多个对象

4

点击查看代码
public class Singleton04 {
  private static Singleton04 INSTANCE = null;

  private Singleton04() {}

  public static Singleton04 getInstance() {
    if (INSTANCE == null) {
      synchronized (Singleton04.class) {
        if (INSTANCE == null) {
          INSTANCE = new Singleton04();
        }
      }
    }
    return INSTANCE;
  }
}
构造对象时可能出现指令重排问题,可能会出现问题

5

点击查看代码
public class Singleton05 {
  private static volatile Singleton05 INSTANCE = null;

  private Singleton05() {}

  public static Singleton05 getInstance() {
    if (INSTANCE == null) {
      synchronized (Singleton05.class) {
        if (INSTANCE == null) {
          INSTANCE = new Singleton05();
        }
      }
    }
    return INSTANCE;
  }
}

6.静态内部类

点击查看代码
public class Singleton06 {

  private Singleton06() {}

  private static class Singleton06Holder {
    private static Singleton06 INSTANCE = new Singleton06();
  }

  public static Singleton06 getInstance() {
    return Singleton06Holder.INSTANCE;
  }
}

7.枚举

点击查看代码
public enum Singleton07 {
  INSTANCE;

  public static Singleton07 getInstance() {
    return INSTANCE;
  }
}
posted @ 2022-08-11 10:47  shigp1  阅读(14)  评论(0编辑  收藏  举报