Java设计模式(四) 单例模式
方式一
package com.pattern.Singleton; public class Singleton { private static Singleton uniqueInstance; private Singleton(){} public static Singleton getInstance(){ if(uniqueInstance == null){ uniqueInstance = new Singleton(); } return uniqueInstance; } }
方式二
package com.pattern.Singleton; public class Singleton2 { private static Singleton2 uniqueInstance = new Singleton2(); private Singleton2(){} public static Singleton2 getInstance(){ return uniqueInstance; } }
方式三
package com.pattern.Singleton; public class Singleton3 { private volatile static Singleton3 uniqueInstance; private Singleton3(){} public static Singleton3 getInstance(){ if(uniqueInstance == null){ synchronized(Singleton.class){ if(uniqueInstance == null){ uniqueInstance = new Singleton3(); } } } return uniqueInstance; } }