Singleton mode (Singleton pattern)

Source: Internet
Author: User

What is Singleton pattern?

In Wikipedia, there was an explanation: "In software engineering, the singleton pattern was a design pattern that re Stricts the instantiation of a class to one object. "

First, what is a singleton mode?

In Wikipedia, this explains, "in software engineering, Singleton mode refers to the restriction of classes, allowing only the design pattern of an object to be created."

That is, in the lifetime of the entire application, there is only one instance of the Singleton class (and of course it may not exist) at any one time.

Singleton mode is an object-creation design pattern, mentioned in the book "Design Patterns: The basics of reusable object-oriented software", in a singleton pattern: " to ensure that a class has only one instance and provides a global access point to access it ."

Let the class itself be responsible for saving its only instance, which guarantees that no other instance is created (by intercepting the request to create the new object).

Second, why should we use the singleton mode?

The singleton mode should be the simplest design pattern in the design pattern, and its application scenario is as follows:

In the process of work, some objects we only need one, such as thread pool, cache, hardware equipment, etc.

If more than one instance is used at the same time, it can cause execution conflicts, inconsistent results, and so on.

For example, we create multiple print program instances, or printer objects, but the actual printing device only one, or print spool only one, the program executes, it can cause the confusion of printing results and the program lost reproducibility.

For example, clicking a menu item in a parent container opens a child window and, if unchecked, opens a new window each time the menu item is clicked. This not only wastes memory resources, but is also unacceptable in the program logic.

So how do we solve this problem? This will use the singleton pattern described in detail below.

Three, the classic single case mode

1. The UML diagram for the classic singleton mode is as follows:

2. The code is implemented as follows:

1  Public classSingleton {2 3     //static instance object, guaranteeing global uniqueness4     Private StaticSingleton instance =NULL;5 6     //private constructors to prevent external creation of instance objects with the New keyword7     PrivateSingleton () {8 9     }Ten  One     //external public static instance method, which can be called directly from the class level A      Public StaticSingleton getinstance () { -  -         //determines whether the object is created by determining whether instance is null the         if(Instance = =NULL) { -Instance =NewSingleton (); -         } -         returninstance; +     } -}

Note: Through the Java reflection mechanism is able to instantiate the construction method as private class, at this time basically all Java Singleton implementation is invalid.

(In fact, we generally do not need to do so, so the singleton mode still has its meaning)

Problems existing in the multi-threaded environment of single-case model

For the above code, we can consider a situation like this:

When there are two instances of the Singleton class being created at the same time and running in different threads. If a thread is accidentally blocked after executing line 15th of the above code, and the B thread continues to run, the instance instance is created after the 16th line is executed, and if the a thread returns to the ready state and gets the processor resources to run, the instance object will be created again, and the singleton mode is invalidated. In order to solve this problem, the programmers have optimized the singleton mode.

V. Classification of single-case patterns

1. A hungry man type single case

The instance is eagerly created and instantiated at the time of class initialization.

1  Public classSingleton1 {2 3     //already instantiated4     Private Static FinalSingleton1 single =NewSingleton1 ();5 6     //private default constructor method7     PrivateSingleton1 () {8     9     }Ten      One     //Static Factory Method A      Public StaticSingleton1 getinstance () { -         returnSingle ; -     } the}

2. Lazy type Single case

Instantiated at the time of the first call.

1  Public classSingleton2 {2 3     //Note that there is no final4     Private StaticSingleton2 single =NULL;5     6     //Private default Construction child7     PrivateSingleton2 () {8     9     }Ten      One     //static Factory method, with synchronized locking A      Public synchronized StaticSingleton2 getinstance () { -          if(single =NULL) { -Single =NewSingleton2 (); the          } -         returnSingle ; -     } -}

This approach also has a certain problem, the same consideration of special circumstances, when a thread execution into the getinstance in an unexpected block, at this time the instance in the B thread is not able to perform the getinstance operation, there is blocking.

In order to solve this problem, the method can be further optimized: double check and lock method.

Although this method is also imperfect, it has been optimized relative to the above situation.

1  Public classSingleton3 {2     3     //Add keyword volatile4     Private volatile StaticSingleton3 single =NULL;5     6     //Private default constructor7     PrivateSingleton3 () {8         9     }Ten      One      Public StaticSingleton3 getinstance () { A          if(single =NULL) { -              //Sync Lock -             synchronized(Singleton3.class) { the                 if(single =NULL) { -Single =NewSingleton3 (); -                 } -             } +         } -         returnSingle ; +     } A}

3. Registration of single-case

Register the class name and get it directly from the inside.

1 ImportJava.util.HashMap;2 ImportJava.util.Map;3 4  Public classSingleton4 {5     Private Staticmap<string,singleton4> map =NewHashmap<string,singleton4>();6     7     Static{8Singleton4 single =NewSingleton4 ();9 Map.put (Single.getclass (). GetName (), single);Ten     } One     //default constructor for protection A     protectedSingleton4 () { -      -     } the      -     //static Factory method to return the unique instance of this type -      Public StaticSingleton4 getinstance (String name) { -         if(Name = =NULL) { +Name = Singleton3.class. GetName (); -         } +         if(Map.get (name) = =NULL) { A             Try { at map.put (name, (Singleton4) class.forname (name). newinstance ()); -}Catch(instantiationexception e) { - e.printstacktrace (); -}Catch(illegalaccessexception e) { - e.printstacktrace (); -}Catch(ClassNotFoundException e) { in e.printstacktrace (); -             } to         } +         returnmap.get (name); -     } the}

Resources:

1. Geek College Hexter Teacher's curriculum--a single case model of design pattern

2. Design mode: The basis of reusable object-oriented software

Erich Gamma,richard Helm,ralph Johnson

3. Blog: Bewitched Into--java single-case model detailed

4. Wikipedia: Singleton Pattern

Recommended reading:

Blog: Zhao Chi-ji @ line speaks louder than words--one of the design pattern training: Why use singleton mode?

Blog: Urban cattle--registration single example to achieve the inheritance of a singleton pattern (qualifying all subclasses of an abstract class must be singleton)

Singleton mode (Singleton 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.