class Singleton{ private Singleton() {} private static Singleton instance = null; public synchronized static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
就利用Sington.getInstace
就可以了,获得的是同一个实例。
上面那个代码有两个优点:
synchronized
修饰这个static
方法,所以相当于给这个方法加上了一个类锁