Java design Pattern--Singleton mode

Source: Internet
Author: User
Tags connection pooling

The singleton pattern can be used as a programming technique, so let's start with the theory and say the code.

Three key points in a singleton mode:

1), a class can have only one instance

2), the class must create this instance on its own

3), the class must provide this instance to the entire system on its own

Application Scenarios:

1), Window Task Manager is a very typical singleton mode, you must not open two Task manager at the same time

2), database connection pooling technology is generally used in singleton mode, because database connection is a kind of database resources. The use of database connection pooling in the system is mainly due to the savings of opening or closing the database connection

Efficiency loss, this loss of efficiency is very expensive, with a single-case mode to maintain, can greatly reduce this loss.

3), when we are developing the configuration file is generally read in the singleton mode, because the content in the configuration file is a globally shared resource.

4), multithreaded thread pool design should also consider a singleton mode, thread pool can facilitate the control of the pool thread.

5), the Website Statistics class information, generally also uses the singleton pattern, otherwise difficult synchronization control, for example statistics my blog's visit quantity.

6), we develop the application of the log function is also used in the singleton mode, because we can only have one instance to append log information, otherwise bad control.

Several types of patterns in a singleton:

1) A hungry man-mode

How to understand, hungry, so we cook to be very anxious, here is to say, when the class is loaded, the class has already created its own instance.

This is also a typical application of space exchange time, how to say? We instantiate this object when the class is loaded, taking up memory space, but we don't have to instantiate it when we use this object.

Just take it with you, and you can save time, which is where space is exchanged for time.

PS: Remember the first job (still in junior time) interview when the interviewer let me cite the project I have done in exchange for space and space for the typical application of time, to me to ask a Meng.

Code:

Package chc.singleton;/** * A hungry man type Singleton mode class * @author Haicheng.cao * @time 2014.09.02 22:40 */public class Eagersingleton {//class loaded It creates its own instance object-The A Hungry man (space for time) public static Eagersingleton eagersingleton=new Eagersingleton ();/** * shows the private constructor method, Prevent other classes from creating instances of this class */private Eagersingleton () {}/** * static Factory method, other classes get the instance object of this class by calling the method */public static Eagersingleton Geteagersingleton () {return Eagersingleton;}}

2) Lazy-mode

How does that make sense? Lazy man, for example, a person will go to the interview to start writing resumes, that is, the object instance to use when the time to create. In this case, the class is loaded without creating a

The instance object of this class is built, but it is created when the other class is called the first time.

This is also a typical time for space applications, that is, the class load without creating objects, saving memory, that is, saving space, call to determine whether this class instance object is stored

In, wasting time, this is the time for space.

Code:

Package chc.singleton;/** * Lazy Singleton mode class * @author Haicheng.cao * @time 2014.09.02 23:05 */public class Lazysingleton {//class loaded You do not create a private constructor that you instantiate the public static Lazysingleton lazysingleton=null;/** * Display to prevent other classes from creating this class instance */private Lazysingleton () {}/* * * Static Factory method, other classes to get the instance object of this class by calling this method */public static synchronized Lazysingleton Getlazysingleton () {/////The first time it is called to create the own instance object if ( Lazysingleton==null) {lazysingleton=new Lazysingleton ();} return Lazysingleton;}}

Note: We have added a sync keyword to the Geteasysingleton () method to ensure thread safety. But does this affect the performance of the program, can we improve it? Look at the following:

3) Double check plus lock

The double check lock mechanism means that we are not in the process of calling the Geteasysingleton () method, we judge whether the instance object exists, if it does not exist, we enter the synchronous generation

code block, this is the first check, enter the synchronization block and then judge, determine whether the instance exists, if there is no more instances of this object, this is the second check. That way, only when the first call

The synchronization code block is executed once, the rest of the time does not need synchronization, improve the performance of the program.

Code:

Package chc.singleton;/** * Double check lock for lazy lifting performance * @author Haicheng.cao * @time 2014.09.02 22:40 */public class Twocheck {
   
    private volatile static Twocheck twocheck = null;        Private Twocheck () {        } public        static Twocheck getinstance () {        ///First check if the instance exists, if it does not exist, enter the following sync block if        (twocheck = = null) {            //sync block, thread-safe Creation instance            synchronized (twocheck.class) {                //check again if the instance exists, if it does not exist to actually create the instance if                (Twocheck = = null) {                Twocheck = new Twocheck ();}}        }        return twocheck;}    }
   

Java design Pattern--Singleton mode

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.