[Design mode] study note 7: Singleton)

Source: Internet
Author: User
Document directory
  • The classic but simple (problematic) implementation of the single-piece mode:

From http://blog.csdn.net/shuangde800

Enter the single-piece Mode

Some objects only need one, such as thread pool, cache, dialog box, processing preferences and registry objects, log objects, and driver objects for printers, graphics cards, and other devices.

The objects of these classes can only have one instance. If there are multiple objects, many problems may occur.

Some people may think that this can be done with either global variables or static variables.

Disadvantages:

Objects must be created at the beginning of the program, but some objects may not be used and consume resources. The single-piece mode is created only when needed.

Single-room mode implementation
The classic but simple (problematic) implementation of the single-piece mode:

Set the constructor to private, and add a static method to create an object and return it.

Public Singleton {Private Static sigleton uniqueinstance; // The constructor is private. Only internal class methods can create private Singleton () {} public static myclass getinstance () {If (uniqueinstance = NULL) {// The object uniqueinstance = new Singleton () ;}return uniqueinstance ;}} is created only when the value is null ;}}


The above practice will cause problems due to the problem of multithreading.

If two threads need to create an object almost simultaneously, the following situation will occur:

Check that both thread one and Thread two have created an object!

Solution 1:

Turning getinstance () into a synchronized method almost easily solves the multi-thread disaster.

Public Singleton {Private Static sigleton uniqueinstance; // The constructor is private. Only internal class methods can create private Singleton () {}// Add the synchronized keyword, it forces each thread to wait for other threads to leave the method before entering this // method. // That is to say, there will not be two threads that can simultaneously enter this method public static synchronized myclass getinstance () {If (uniqueinstance = NULL) {// The object uniqueinstance = new Singleton () ;}return uniqueinstance ;}} is created only when the value is null ;}}


Disadvantage: every time you use this method, synchronization will reduce the performance of the program. Synchronizing a method may reduce the execution efficiency by 100 times.


Solution 2: eager instantiation
Public Singleton {// create a single piece in the static initializer // ensures thread safety Private Static sigleton uniqueinstance = new Singleton (); // The constructor is private. Only internal class methods can be used to create a class private Singleton () {} public static synchronized myclass getinstance () {return uniqueinstance ;}}
Solution 3: Use "double check and lock" to reduce the use of synchronization in getinstance ()

Use double-checked locking to check whether the instance has been created.

In this way, only synchronization will be performed for the first time and no more

Public Singleton {// note that the volatile keyword is added here // make sure that: when the uniqueinstance variable is initialized to a singleton instance, // multiple threads correctly process the uniqueinstance variable Private Static volatile sigleton uniqueinstance; private Singleton () {} public static synchronized myclass getinstance () {If (uniqueinstance = NULL) {synchronized (Singleton. class) {If (uniqueinstance = NULL) {uniqueinstance = new Singleton () ;}} return uniqueinstance ;}}

Note! The double check lock is not used for Java 1.4 or earlier versions.

Define single-piece Mode

Single-piece mode ensures that one class has only one instance and provides a Global Access Point

Class Diagrams in single-piece mode are simple

Global variables vs single-piece Mode

In Java, global variables are basically static references to objects.

In this case, using global variables has some disadvantages. We have mentioned the following: eager instantiation vs. Delayed instantiation.

But remember the purpose of this mode: ensure that the class has only one instance and provides global access.

Global variables also encourage developers in disguise to point many global variables to many small objects to cause namespace pollution.

The single-piece mode does not encourage such a phenomenon, but the single-piece mode may still be abused.

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.