--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方法,所以相当于给这个方法加上了一个类锁

相关文章: