设计模式之单例模式

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

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 @   shigp1  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示