A singleton pattern of common Java design Patterns

Source: Internet
Author: User

1. What is a singleton mode?

Singleton mode is a kind of common software design pattern. In its core structure, it contains only a special class called a singleton class. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system. The singleton mode ensures that a class has only one instance, provides this instance on its own and provides this instance to the system as a whole.

2. How to implement the singleton mode

in general, the single-case design mode has three specific implementation methods, namely, lazy mode, hunger and Han mode and double lock design mode.

Here we will introduce them separately:

1. Lazy mode

Lazy-type is a typical time to change space, that is, every time you get an instance will be judged to see if you need to create an instance, wasting judgment time. Of course, if no one ever uses it, it doesn't create an instance, which saves memory space.

The Java code example is as follows:

Package com.yonyou.test; /** * Use lazy mode to create a singleton mode * @author Small Hao * @ Creation date 2015-4-4 */public class Singleton {private static Singleton Back or create a related singleton instance * @return */public static synchronized Singleton getinstance () {//Use synchronous method to ensure thread safety if (instance==null) {instance =new Singleton ();} return instance;} /*** a private construction method so that external objects cannot be new related instances, * this is especially important to note that the default method of privatization must be provided to override the default construction method otherwise, if the user goes directly to the new object *, there is no guarantee that the singleton ~~~*/private Singleton () {}}

I see this code feel can also, has basically implemented a single case design pattern, but if we carefully examine, we will find the problem lies.

In the Code

public static synchronized Singleton getinstance () {//Use synchronous method to ensure thread safety

Here we see that each time the acquisition of a single case will be added to the synchronization lock, which will inevitably lead to the problem of access performance.

In order to better solve this problem, we can modify the location to join the sync lock, see the following code:

Package com.yonyou.test;  /** * Use lazy mode to create a singleton mode * @author Small Hao * @ Creation date 2015-4-4 */public class Singleton {private static Singleton Back or create a related singleton instance * @return */public static Singleton getinstance () {if (instance==null) {    ///Join a synchronous code block, which effectively handles concurrent access problems    synchronized (singleton.class) {            if (instance==null) {            instance=new Singleton ();}}      } return instance;} /*** a private construction method so that external objects cannot be new related instances, * this is especially important to note that the default method of privatization must be provided to override the default construction method otherwise, if the user goes directly to the new object *, there is no guarantee that the singleton ~~~*/private Singleton () {}}

  

In addition, there is a comparison to the implementation of a single example of the way, recommend that you use this method:

Google's engineer, Bob Lee, wrote the new lazy singleton pattern, where the singleton pattern was implemented on the basis of an internal class,the corresponding thread safety is done by the JVM static initializer.

Package com.yonyou.test;  /** * Using lazy mode to create a singleton mode * @author Small Hao * @ Creation date 2015-4-4 */public class Singleton {     /*** class-level inner class, that is, a static member-inner class, an instance of the inner class and an instance of an external class * There is no binding, and it is loaded only when it is called, allowing for lazy loading. */static   class Singletonholder {        /**    *  quiescent initializer, guaranteed thread safety by the JVM *    /     static Singleton instance = new Singleton ();           }           public static Singleton getinstance () {            return singletonholder.instance;      }     /**  * A private construction method that makes external objects not new related instances,  * This particular note, be sure to provide a default privatization method to override  the default constructor method otherwise, if the user goes directly to the new object  * , there is no guarantee of a single case ~ ~ ~  

  

3. Design mode of a hungry man

in the process of initializing the class will complete the initialization of the relevant instance, generally think that this way to be more secure, a hungry man-style is a typical space-time, when the class loading will create an instance of the class, no matter you do not use, first created, and then each call, there is no need to judge, Saves time in running.

The Java code example is as follows:

Package com.yonyou.test; /** * Create a singleton pattern using the Famine mode * @author Small Hao * @ Creation date 2015-4-4 */public class Singleton {//Initialize Singleton instance when loading class private final static Singleton instance=new Singleton ()/*** Returns or creates an associated singleton instance * @return */public static Singleton getinstance () {      return instance;} /*** a private construction method so that external objects cannot be new related instances, * this is especially important to note that the default method of privatization must be provided to override the default construction method otherwise, if the user goes directly to the new object *, there is no guarantee that the singleton ~~~*/private Singleton () {}}

  

A singleton pattern of common Java design Patterns

Related Article

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.