Java design pattern-Singleton mode

Source: Internet
Author: User

1. Definition

Singleton mode (Singleton), 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.

Characteristics

    1. Singleton mode can have only one instance.

    2. The Singleton class must create its own unique instance.

    3. The Singleton class must provide this instance to other objects.

2. Pros and cons

Advantages:
1. In the singleton mode, the active singleton has only one instance, and all instances of the Singleton class are given the same instance. This prevents other objects from instantiating themselves, ensuring that all objects have access to an instance
2. The singleton mode has a certain scalability, the class itself to control the instantiation process, the class in the process of changing the instantiation has the corresponding flexibility.
3. Provides controlled access to a unique instance.
4. Because there is only one object in system memory, system resources can be saved, and the singleton mode can undoubtedly improve the performance of the system when objects that need to be created and destroyed frequently.
5. Allow a variable number of instances.

6. Avoid multiple uses of shared resources.

Disadvantages:
1. Not applicable to changing objects, if the same type of object is always to be changed in different use case scenarios, the singleton will cause data errors, cannot save each other's state.
2. Because there is no abstraction layer in the simple interest mode, the expansion of the Singleton class is very difficult.
3. The duty of the Singleton class is too heavy to a certain extent contrary to the "single principle of responsibility".

4. The misuse of the singleton will bring some negative problems, such as a singleton class designed to conserve resources for the database connection pool object, which could result in a connection pool overflow for programs that share connection pool objects, and if the instantiated objects are not exploited for a long time, the system is considered garbage and is recycled, which results in the loss of the object state.

3. Code implementation

1. Lazy, thread insecure

 Public class Singleton {    privatestatic  Singleton instance;    Private Singleton () {}      Public Static Singleton getinstance () {        ifnull) {            new  Singleton ();      }         return instance;}   }

2. Lazy, Thread-safe

 Public class Singleton {    privatestatic  Singleton instance;    Private Singleton () {}      Public Static synchronized Singleton getinstance () {        ifnull) {            new  Singleton ();      }         return instance;   

3. A Hungry Man

 Public class Singleton {    privatestaticnew  Singleton ();    Private Singleton () {}      Public Static Singleton getinstance () {        return  instance;   }}

4. A hungry man, variant

 Public class Singleton {    privatestaticnew  Singleton ();    Private Singleton () {}      Public Static Singleton getinstance () {        return  instance;   }}

5. Static Inner class

 public  class   Singleton { private  static  class   Singletonholder {private  static  final    Singleton INSTANCE = new   Singleton ();  private   Singleton () {}  public  static  final   Singleton getinstance () { return   singletonholder.instance; }}

6. Enumeration

 Public enum Singleton {    INSTANCE;     Public void Whatevermethod () {    }}

7. Double check Lock

 Public classSingleton {Private volatile StaticSingleton Singleton; PrivateSingleton () {} Public StaticSingleton Getsingleton () {if(Singleton = =NULL) {            synchronized(Singleton.class) {                if(Singleton = =NULL) {Singleton=NewSingleton (); }            }        }        returnSingleton; }}

4. Summary

    1. Class has only one instance

    2. Class must provide a globally unique accessible point

Follow the public number "Java trade union" to get more technical dry goods!

Join QQ Group 727096055, Ali great God and you talk about technology!

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.