"Onlookers" design mode (7)--Create a singleton pattern (Singleton pattern)

Source: Internet
Author: User

Singleton mode, also known as the list mode, is a common software design pattern . When you apply this pattern, the class of the Singleton object must guarantee that only one instance exists. Many times the entire system needs to have only one global object , which helps us coordinate the overall behavior of the system. For example, in a server program, the configuration information for this server is stored in a single file , which is read uniformly by a singleton object, and then the other objects in the service process are then given the configuration information through this singleton object. This approach simplifies configuration management in complex environments. ----Wikipedia (Wikipedia)


Personal Understanding:

Singleton mode concept is simple, his purpose is to allow only one instance of this class, often used in the JDBC operation class, etc., where I apply to the project is used to get the DAO layer of the class instance, the singleton pattern has a variety of implementations, here I recognize the A hungry man type, lazy, enumeration, static inner class. Fortunately, the finishing process, because also expanded a lot of the single-mode knowledge.


Here's a look at the actual example:



Lazy Type


</pre><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:12PX;" ></span></span><pre name= "code" class= "Java" >public class Singleton01 {private static Singleton01 singleton = null;private Singleton01 () {}public static Singleton01 getinstance () {if (singleton = = null) Singleton = new Singleton01 (); return singleton;}}


thread is unsafe, when multiple threads call the GetInstance method at the same time, both detect that Singleton is null and then start creating the object, creating multiple instances instead of one.

public class Singleton02 {private static Singleton02 singleton = Null;private Singleton02 () {}public synchronized static Si Ngleton02 getinstance () {if (singleton = = null) Singleton = new Singleton02 (); return singleton;}}

This example is thread-safe, and multiple threads do not create multiple object instances at the same time, but are not very efficient and require multiple threads to execute the method sequentially.

public class Singleton03 {private static Singleton03 singleton = Null;private Singleton03 () {}public static Singleton03 get Instance () {if (singleton = = null) synchronized (Singleton03.class) {if (singleton = = null) {singleton = new Singleton03 ();}} return singleton;}}

This method is called double check (double check), compared to the classic design, why should it be two times? First of all, the outside of the judgment is to avoid the object has been created, you do not have to synchronize the creation of the object, the second is to prevent the first time you have not created an instance, multiple threads are already waiting, this time needs to be empty judgment. Prevent subsequent field entry after waiting to create the instance again.


Reference to other people's article "1":

Singleton = new Singleton () is not an atomic operation, and roughly three things are done in the JVM:

1. Allocate memory to instance.

2. Initialize the member variable through its constructor.

3. Point the instance to the allocated memory space. (the instance is not null after execution).

However, in the JVM compiler there is an optimization of order reordering, the final order of execution is 1-3-2, if it is 1-3-2, then after 3 execution, 2 execution, thread A by thread B steals, instance non-empty, thread B will directly return instance, This time, the direct use will be error.

The solution given (using the volatile keyword masking) is:

public class Singleton03 {private volatile static Singleton03 singleton = Null;private Singleton03 () {}public static single Ton03 getinstance () {if (singleton = = null) synchronized (Singleton03.class) {if (singleton = = null) {singleton = new Singleton03 ();}} return singleton;}}


a hungry man type


public class Singleton04 {private static final Singleton04 singleton = new Singleton04 ();p rivate Singleton04 () {}public sta Tic Singleton04 getinstance () {return singleton;}}

This approach is thread-safe, but the disadvantage is that even if the GetInstance method is not called, his instance will be generated. Before the lazy way is lazy to load the idea, when needed to create.



static inner class


public class Singleton05 {private static class Singleton{private static final Singleton05 instance = new Singleton05 ();} Private Singleton05 () {}public Singleton05 getinstance () {return singleton.instance;}}
The static inner class is used, the private static inner class is inaccessible externally, similar to the A Hungry man form, but it is improved on this basis, the A Hungry man style is the internal property used, and this isconstant of the static inner class used.


Enumeration

God-like design, there are several reasons for using enumerations to implement singleton patterns:

1. Free serialization

2. Thread Safety

3. Ensure that there is only one instance.

public enum Singleton06 {instance;private Singleton06 () {}public void print () {System.out.println ("enum singleton!");}}

Call:


Singleton06.INSTANCE.print ();


code Download

Download code


Reference

"1" http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/


"Onlookers" design mode (7)--Create a singleton pattern (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.