--here--gold--you--want

一:之前旧的写法

class Singleton{
    private Singleton() {}
    private static Singleton instance = null;
    public synchronized static Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
}

就利用Sington.getInstace就可以了,获得的是同一个实例。上面那个代码有两个优点:

  1. 懒加载,把在堆创建实例这个行为延迟到类的使用时。
  2. 锁效果,防止生成多个实例,因为synchronized修饰这个static方法,所以相当于给这个方法加上了一个类锁

相关文章:

  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2021-10-27
  • 2022-12-23
  • 2021-08-14
  • 2021-11-30
  • 2022-02-02
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2021-08-14
相关资源
相似解决方案