Design Mode: Singleton)

Source: Internet
Author: User

Design Mode: Singleton)

 What is Singleton mode?

A class has only one instance, which is automatically instantiated by the system and provided to the entire system through a global access point.

Why is Singleton mode used?

Memory saving. You do not need to instantiate an object every time you use it. An instance is provided globally to reuse resources. In some environments, it is very important to ensure that the class has only one instance. For example: job Manager in windows.

How to Use Singleton mode?
The Singleton mode has a variety of writing methods, which ultimately cannot escape the following three key points:

One and only one instance does not need to be manually created and is automatically instantiated by the system.

Provides the entire system with a unique global access point

In addition, there may be different requirements in different environments: Ensure thread security, ensure serialization, do not generate multiple instances during deserialization, and generate multiple instances during loading of multiple class loaders.

First implementation:

public class Singleton {    private static Singleton singleton = null;    private Singleton(){    }    public static Singleton getInstance(){         if(singleton == null){             singleton = new Singleton();        }         return singleton ;    }}
This type of Singleton instantiation is performed only when it is needed, but it has obvious disadvantages: 1. The thread is not secure enough. 2. You need to determine whether the instance has been instantiated every time you use it, the first disadvantage is that you can use synchronized to declare the getInstance method. The second disadvantage can be avoided using the second implementation.

Second Implementation:

public class Singleton {    private static Singleton singleton = new Singleton();    private Singleton(){    }    public static Singleton getInstance(){         return singleton ;    }}
The instantiation of this Singleton is based on the classloader mechanism, which avoids the security of multiple threads and does not need to determine whether the instance has been instantiated during each usage. This is the most common method. Similar implementations can also use static blocks to instantiate a single instance.

Third Implementation:

public class Singleton {     private static class SingletonHolder {          private static final Singleton INSTANCE = new Singleton();     }     private Singleton (){}     public static final Singleton getInstance() {     return SingletonHolder. INSTANCE;     } }
This implementation Singleton class is loaded, and the instance is not necessarily initialized. Because the SingletonHolder class is not actively used, the SingletonHolder class is displayed and instantiated only when the getInstance method is called.

Fourth Implementation:

public enum  Singleton{    SINGLETON;     public void doWhatever(){};}
This implementation is implemented using enumeration, which can avoid multi-thread synchronization and prevent repeated object creation in deserialization. However, enumeration is a new feature added in JDK, therefore, it is rare to see that someone is using it in real projects.

Fifth implementation:

public class Singleton {     private volatile static Singleton singleton;     private Singleton (){}     public static Singleton getSingleton() {         if (singleton == null) {             synchronized (Singleton. class) {             if (singleton == null) {                 singleton = new Singleton();             }             }         }         return singleton ;     } } 

A way of writing that has been abandoned, specific timestamps ....
 

In addition, when reading an uncle bob article about Singleton and "creating only one instance", he provides another feasible method:

public class   Singleton {     private Singleton(){}     public static NonSingleton nonSingleton = newNonSingleton( new Singleton());}public class   NonSingleton {     public NonSingleton(Singleton singleton) {         assert (singleton != null);    }     public void doWhatever(){    }}
This is mainly because uncle bob believes that the singleton mode violates the SRP (single responsibility principle), that is, the principle that one class only does one thing, this implementation separates Singleton instantiation and Singleton operations.

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.