A singleton pattern for the Java Design Pattern series

Source: Internet
Author: User

Definition of a singleton pattern

A class has and has only one instance, and self-instantiation is provided to the system as a whole. For example, when multiple programs read a configuration file, it is recommended that the configuration file be encapsulated as an object when the configuration file is suggested. It is easy to manipulate the data, and to ensure that multiple programs read the same profile object, it is necessary that the profile object is unique in memory.

The role of the singleton pattern

In short, a singleton pattern (also called a single-piece mode) is a guarantee for the entire application life cycle, at any one time, only one instance of a singleton class exists (or it can not exist).

Class diagram of a singleton pattern

How to guarantee the uniqueness of an object

Thought: (1) do not allow other programs to create such objects;

(2) Create a class object in this class;

(3) To provide methods to other programs to obtain this object;

Steps: (1) because the constructor initialization is required for creating objects, as long as the constructors in this class are privatized, other programs can no longer create objects of that class;

(2) Create an object of this class in the class;

(3) Define a method that returns the object so that other programs can obtain the object of this class by means of the method (function: Controllable, the generation of objects of this class is determined by themselves, no one wants new on new)

"Tenderness hint": If we write code like this, the client gets to the GetInstance method can not also get a lot of class object? Isn't that a singleton?

1  Public class Car {23     Private Car () {4         5     }6public     static  Car getinstance () {7          returnnew  Car (); 8     }9 }

So we directly create an object ourselves in the class, the GetInstance method is only responsible for returning the object to the caller, fully implementing the singleton control (you can get my method, but I can get the object I created)

1  Public classCar {2 3     Private StaticCar car=NewCar ();4     PrivateCar () {5         6     }7      Public StaticCar getinstance () {8         returncar;9     }Ten}

The code reflects:

(1) Privatization of constructors

(2) Create a private and static object of this class

(3) Define a public and static method to return the object;

There are two main ways of code implementation: a hungry man mode and lazy mode

A hungry man mode: When the class is loaded, the object already exists, the A hungry man is thread-safe, and at the same time the class is created a static object is created for the system to use, and no longer changes. Why is it thread-safe? We'll explain later.

1  Public classSingle {2 3     Private StaticSingle s=NewSingle ();4     PrivateSingle () {5         6     }7      Public StaticSingle getinstance () {8         returns;9     }Ten}

Lazy mode: Class loading when the object does not exist, is called the lazy loading mode, need to create again, lazy-type if you create an instance object without synchronized, it will cause access to the object is not thread-safe (a bit confused?). It doesn't matter, it will be understood later, first on the code)

1  Public classSingle {2 3     Private StaticSingle =NULL;4 5     PrivateSingle () {6 7     }8 9      Public StaticSingle getinstance () {Ten         if(single =NULL) { OneSingle =NewSingle (); A         } -         returnSingle ; -     } the}

Below we explain that lazy thread is unsafe, usually we recommend writing a hungry man, because it is thread-safe.
When multi-threaded access to lazy-type, because of the lazy way of the common data in the operation of multiple statements.

Two threads, line Cheng and line Cheng call the GetInstance method at the same time, when thread 1 executes the If judgment, single is empty, there is no time to execute a single =new a single () to create the object, the thread 2 is coming, it also performs if judgment, Single is still empty, then create an object, two threads will create two objects, contrary to our singleton mode of the original intention, how to solve it?

Thread safety issues, in order to solve this problem, join the synchronization mechanism (not familiar with the synchronization mechanism of Baidu Bar): Static synchronization function of the lock is the class bytecode file object

  

            

Well, to here, the real example of the introduction of the model, and then summarize the single-case class need to pay attention to the points:

The singleton pattern is used to implement only one instance of the entire program.

The constructor of a singleton class must be private, and the Singleton class must provide a global access point.

Three, the single-case mode in the multi-threaded synchronization problem and the performance problem resolution.

Four, lazy-type and a hungry man-type single-case class.

A singleton pattern for the Java Design Pattern series

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.