Design Mode-singleton mode (1)

Source: Internet
Author: User

The idea for implementing the singleton mode is:

1. A class can return a reference to an object (always the same) and a method to obtain the instance (it must be a static method, usually using the getInstance name );

2. When we call this method, if the reference held by the class is not null, this reference is returned, if the reference of the class persistence is null, create an instance of the class and assign the instance reference to the reference of the class persistence;

3. At the same time, we also define the constructor of this class as a private method, so that code in other places cannot call the constructor of this class to instantiate the object of this class, only the static method provided by this class is used to obtain the unique instance of this class.


1. Hunger. A global Singleton instance is built during class loading. It is initialized when the class is loaded into the memory for the first time. Therefore, the instance created is thread-safe.


Package com. open. design. singleton;/*** hunger style * @ author Administrator **/public class Singleton1 {private final static Singleton1 instance = new Singleton1 (); private Singleton1 () {} public static Singleton1 getInstance () {return instance ;}}


Package com. open. design. singleton;/*** is a hungry class, static initialization. * @ Author Administrator **/public class Singleton5 {private static final Singleton5 instance; static {try {instance = new Singleton5 ();} catch (Exception e) {throw new RuntimeException ("Darn, an error occurred! ", E) ;}} private Singleton5 () {} public static Singleton5 getInstance () {return instance ;}}



2. Lazy.

Package com. open. design. singleton;/*** lazy Mode 1 * @ author Administrator **/public class Singleton2 {private static Singleton2 instance = null; private Singleton2 () {} public static Singleton2 getInstance () {if (instance = null) {instance = new Singleton2 () ;}return instance ;}}

Package com. open. design. singleton;/*** lazy method 2 * @ author Administrator **/public class Singleton3 {private static Singleton3 instance = null; private Singleton3 () {} public static synchronized Singleton3 getInstance () {if (instance = null) {instance = new Singleton3 () ;}return instance ;}}



Package com. open. design. singleton;/*** lazy Mode 3 * @ author Administrator **/public class Singleton4 {private static volatile Singleton4 INSTANCE = null; // Private constructor suppresses // default public constructor private Singleton4 () {}// thread safe and performance promote public static Singleton4 getInstance () {if (INSTANCE = null) {synchronized (Singleton4.class) {// when more than two threads run into the first null check same time, to avoid instanced more than one time, it needs to be checked again. if (INSTANCE = null) {INSTANCE = new Singleton4 () ;}} return INSTANCE ;}}

(Lazy method 3 can only be used in JDK 5 and later versions (note that the INSTANCE is declared as volatile). In earlier versions, using the "double check lock" will lead to unexpected behavior [1])


3. VM synchronization guarantee. Full use of the Java Virtual Machine mechanism for synchronization guarantee, there is no synchronization keyword. This method is because the Singleton class is loaded and the instance is not necessarily initialized. Because the SingletonHolder class is not actively used, the SingletonHolder class is displayed and instantiated only when the getInstance method is called.

Package com. open. design. singleton;/*** the Java VM mechanism is fully used for synchronization, without a keyword for synchronization. * @ Author Administrator **/public class Singleton6 {// Private constructor prevents instantiation from other classesprivate Singleton6 () {}/ *** SingletonHolder is loaded on the first execution of Singleton. getInstance () * or the first access to SingletonHolder. INSTANCE, not before. */private static class SingletonHolder {public static final Singleton6 INSTANCE = new Singleton6 ();} public static Singleton6 getInstance () {return SingletonHolder. INSTANCE ;}}

4. enumeration. By default, enumeration creation is thread-safe, which is applicable to jdk 1.5 and later versions.

Package com. open. design. singleton;/*** Enumeration Method * @ author Administrator **/public enum Singleton7 {INSTANCE ;}





1. for reflection problems, except for enumeration tickets, other Singleton methods can obtain new Singleton objects through reflection.

Package com. open. design. singleton; import java. lang. reflect. constructor; public class TestSingleton {/*** @ param args */public static void main (String [] args) {testSingleton1 (); testSingleton2 (); testSingleton3 (); testSingleton4 (); testSingleton5 (); testSingleton6 (); testSingleton7 ();} public static void testSingleton1 () {Singleton1 ins = Singleton1.getInstance (); // get the first instance System. out. println (ins); Singleton1 I NS2. = null; // use reflection to get the second instance. You must write the full path when referencing the Class here. Otherwise, the system reports that the Class try {Class c = Class cannot be found. forName ("com. open. design. singleton. singleton1 "); Constructor [] con = c. getDeclaredConstructors (); Constructor conc = con [0]; conc. setAccessible (true); ins2 = (Singleton1) conc. newInstance (); System. out. println (ins2);} catch (Exception e) {e. printStackTrace ();} System. out. println ("testSingleton1:" + (ins. equals (ins2 )? "Same": "diff"); System. out. println ();} public static void testSingleton2 () {Singleton2 ins = Singleton2.getInstance (); // obtain the first instance System. out. println (ins); Singleton2 ins2 = null; try {Class c = Class. forName ("com. open. design. singleton. singleton2 "); // use reflection to obtain the second instance. You must write the full path when referencing the class here. Otherwise, the Constructor [] con = c. getDeclaredConstructors (); Constructor conc = con [0]; conc. setAccessible (true); ins2 = (Singleton2) conc. new Instance (); System. out. println (ins2);} catch (Exception e) {e. printStackTrace ();} System. out. println ("testSingleton2:" + (ins. equals (ins2 )? "Same": "diff"); System. out. println ();} public static void testSingleton3 () {Singleton3 ins = Singleton3.getInstance (); // obtain the first instance System. out. println (ins); Singleton3 ins2 = null; try {Class c = Class. forName ("com. open. design. singleton. singleton3 "); // use reflection to obtain the second instance. You must write the full path when referencing the class here. Otherwise, the Constructor [] con = c. getDeclaredConstructors (); Constructor conc = con [0]; conc. setAccessible (true); ins2 = (Singleton3) conc. new Instance (); System. out. println (ins2);} catch (Exception e) {e. printStackTrace ();} System. out. println ("testSingleton3:" + (ins. equals (ins2 )? "Same": "diff"); System. out. println ();} public static void testSingleton4 () {Singleton4 ins = Singleton4.getInstance (); // obtain the first instance System. out. println (ins); Singleton4 ins2 = null; try {Class c = Class. forName ("com. open. design. singleton. singleton4 "); // use reflection to obtain the second instance. You must write the full path when referencing the class here. Otherwise, the Constructor [] con = c. getDeclaredConstructors (); Constructor conc = con [0]; conc. setAccessible (true); ins2 = (Singleton4) conc. ne WInstance (); System. out. println (ins2);} catch (Exception e) {e. printStackTrace ();} System. out. println ("testSingleton4:" + (ins. equals (ins2 )? "Same": "diff"); System. out. println ();} public static void testSingleton5 () {Singleton5 ins = Singleton5.getInstance (); // obtain the first instance System. out. println (ins); Singleton5 ins2 = null; try {Class c = Class. forName ("com. open. design. singleton. singleton5 "); // use reflection to obtain the second instance. You must write the full path when referencing the class here. Otherwise, the Constructor [] con = c. getDeclaredConstructors (); Constructor conc = con [0]; conc. setAccessible (true); ins2 = (Singleton5) conc. new Instance (); System. out. println (ins2);} catch (Exception e) {e. printStackTrace ();} System. out. println ("testSingleton5:" + (ins. equals (ins2 )? "Same": "diff"); System. out. println ();} public static void testSingleton6 () {Singleton6 ins = Singleton6.getInstance (); // obtain the first instance System. out. println (ins); Singleton6 ins2 = null; try {Class c = Class. forName ("com. open. design. singleton. singleton6 "); // use reflection to obtain the second instance. You must write the full path when referencing the class here. Otherwise, the Constructor [] con = c. getDeclaredConstructors (); Constructor conc = con [0]; conc. setAccessible (true); ins2 = (Singleton6) conc. new Instance (); System. out. println (ins2);} catch (Exception e) {e. printStackTrace ();} System. out. println ("testSingleton6:" + (ins. equals (ins2 )? "Same": "diff"); System. out. println ();} public static void testSingleton7 () {Singleton7 ins = Singleton7.getInstance (); // obtain the first instance System. out. println (ins); Singleton7 ins2 = null; try {Class c = Class. forName ("com. open. design. singleton. singleton7 "); // use reflection to obtain the second instance. You must write the full path when referencing the class here. Otherwise, the Constructor [] con = c. getDeclaredConstructors (); Constructor conc = con [0]; conc. setAccessible (true); ins2 = (Singleton7) conc. new Instance (); System. out. println (ins2);} catch (Exception e) {e. printStackTrace ();} System. out. println ("testSingleton7:" + (ins. equals (ins2 )? "Same": "diff"); System. out. println ();}}

Check the printed results. If the enumeration type Singleton fails to be obtained through reflection, the reflection is successful in other Singleton forms, which proves that the enumeration type is the safest.

Html
Http://blog.csdn.net/kerryyw/article/details/7237821
Http://sucre.blog.51cto.com/1084905/569511
Http://www.blogjava.net/kenzhh/archive/2013/03/15/357824.html


Address: https://github.com/zz7zz7zz/design-pattern



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.