package com.singleton; /** * Only once instance of the class may be created during the * execution of any given program. Instances of this class should * be aquired through the getInstance() method. Notice that there * are no public constructors for this class. */ public class HungrySingleton { /** * @label Creates */ private static HungrySingleton m_instance = new HungrySingleton(); private HungrySingleton() { } public static synchronized HungrySingleton getInstance() { return m_instance; } }
package com.singleton; /** * Only once instance of the class may be created during the * execution of any given program. Instances of this class should * be aquired through the getInstance() method. Notice that there * are no public constructors for this class. */ public class lazySingleton { /** * @label Creates */ private static lazySingleton m_instance = null; private lazySingleton() { } public static synchronized lazySingleton getInstance() { if (m_instance == null) { m_instance = new lazySingleton(); } return m_instance; } }
package com.singleton; /** * 採用內部類的方式實現單例 * @author LLS * */ public class RegisterSingleton { /* * 私有構造方法,防止被外類實例化 */ private RegisterSingleton(){} /* * 公開方法 */ public static RegisterSingleton getInstance() { return Holder.instance; } /* * 私有內部類 */ private static class Holder { private static final RegisterSingleton instance=new RegisterSingleton(); } }