Java programmers from stupid birds to cainiao () big talk design pattern (3) Singleton pattern

Source: Internet
Author: User

This article is from: Cao shenghuan blog column. Reprinted please indicate the source:Http://blog.csdn.net/csh624366188

 

 

The Singleton mode is an object creation mode. Its intention is to ensure that a class has only one instance and provide a global access point to it. For some classes, it is very important to have only one instance. Although many printers can exist in the system, only one printer should be taken offline, there should be only one file system and one window manager. A digital filter can only have one A/D converter, and an accounting system can only be dedicated to one company. How can we ensure that a class has only one instance and this instance is easy to access? A global variable makes an object accessible, but it cannot prevent you from instantiating multiple objects, A better way is to let the class itself store its unique instance. This class can ensure that no other instance can be created, and it can provide a method to access the instance, which is the singleton mode.

Highlights of Singleton Mode

First, a class can only have one instance;

Second, it must create the instance on its own;

Third, it must provide the instance to the entire system.

Practicality: The Singleton mode can be used in the following cases.

L when the class can only have one instance and the customer can access it from a well-known access point.

L when this unique instance should be extensible through subclass, and the customer should be able to use an extended instance without changing the code.

Class diagram:

As shown in the preceding class diagram, the singleton constructor is used in the singleton class,

However, this constructor is private (with the "-" symbol in front ),

Then, a getinstance () method is also published in it,

The preceding class diagram shows the features of the singleton mode, and defines the singleton mode as follows:The Singleton mode ensures that one class has only one instance, and the class must also provide a global access point to access the class.

 

The following is from

The Singleton mode can be divided into two types based on the time of instantiating objects: one is the hungry Chinese Singleton, and the other is the lazy Chinese Singleton. When a hungry Chinese Singleton class is loaded, an object is instantiated and handed over to its own reference. The Lazy class instantiates an object only when calling the instance method. The Code is as follows:

Hungry Chinese Singleton

 public class Singleton {       private static Singleton singleton = new Singleton();       private Singleton(){}       public static Singleton getInstance(){           return singleton;       }   }  

Lazy Singleton

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

Advantages of Singleton mode:

· There is only one object in the memory, saving memory space.

· Avoiding frequent object creation and destruction can improve performance.

· Avoid multiple usage of shared resources.

· Global access.

Applicable scenarios: Because of the advantages of the singleton mode, it is a design mode that is used in programming. I have summarized the scenarios that I know are applicable to the singleton mode:

· Objects that need to be frequently instantiated and then destroyed.

· Objects that are frequently used when creating objects that are time-consuming or resource-consuming.

· Stateful tool objects.

· Objects that frequently access databases or files.

· And other scenarios that require only one object.

Considerations for Singleton mode:

· You can only obtain the singleton object using the method provided by the singleton class. Do not use reflection. Otherwise, a new object will be instantiated.

· Do not perform dangerous operations to disconnect a singleton class object from static reference in the class.

· Pay attention to thread security issues when using shared resources in multiple-threaded use cases.

Some disputes over Java Singleton mode:

Will objects in singleton mode not be collected by the JVM Garbage Collector for a long time?

According to many materials, if a singleton object is not used in the memory for a long time, it will be considered as a garbage by JVM and will be cleared when garbage collection is executed. I am skeptical about this. My opinion is: In the hotspot virtual machine version 1.6, unless the link to the singleton object statically referenced in the singleton instance is artificially disconnected, otherwise, the JVM garbage collector will not recycle the singleton object.

For this controversy, I have written an article separately for discussion. If you have different ideas or have had experiences in this area, please go to the singleton mode article for discussion: singleton mode and spam are discussed.

 

Will multiple Singleton instances appear in one JVM?

In the case of a distributed system, multiple classloaders, and serialization, multiple Singleton instances are generated, which is non-trivial. In the same JVM, will a singleton be generated? The getinstance () method provided by the singleton can only obtain the same singleton. A new Singleton will be obtained unless the reflection method is used. The Code is as follows:

Class C = Class. forname (singleton. Class. getname ());

Constructor Ct = C. getdeclaredconstructor ();

Ct. setaccessible (true );

Singleton = (Singleton) CT. newinstance ();

In this way, a new singleton object will be generated every time you run it. Therefore, when using the singleton mode, be sure not to use reflection to generate new Singleton objects.

 

Loose Singleton thread security?

The lazy Singleton mode is thread insecure. Even if the synchronized keyword is added to the method of instantiating an object, it is still dangerous. However, I have tested the code, after synchronized keyword modification is found, although it has some impact on the performance, it is thread-safe and does not produce the situation of instantiating multiple objects.

 

Is the singleton mode available only for the hungry and lazy modes?

Hunger and laziness are only two mainstream and common Singleton mode methods. Theoretically, any design mode that can implement one class has only one instance, can be called the singleton mode.

 

Can a singleton class be inherited?

The constructor is private, so they cannot be inherited, but many other Singleton modes can be inherited, such as the registered Singleton.

 

Good for a hungry Chinese-style Singleton or a lazy Chinese-style Singleton

In Java, the ELE. Me Singleton is better than the lazy Singleton. In C ++, the lazy Singleton is generally used.

The Singleton mode is relatively simple, so the sample code is not demonstrated here.

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.