利用static来实现单例模式
时间:2022-01-09 作者:--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; } }
就利用域名nstace就可以了,获得的是同一个实例。上面那个代码有两个优点:
- 懒加载,把在堆创建实例这个行为延迟到类的使用时。
- 锁效果,防止生成多个实例,因为synchronized修饰这个static方法,所以相当于给这个方法加上了一个类锁