Analysis of Singleton mode and design mode in Design Mode

Source: Internet
Author: User

Analysis of Singleton mode and design mode in Design Mode

Singleton mode is a common software design mode. Its main function is to ensure that a class can only have one instance of this class. The problem solved is that a global class is frequently created and destroyed. You can use it when you want to control the number of instances and save system resources.
The Singleton mode has three key points:
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.

Next I will introduce in detail the six writing methods of the Order example and their respective features:
Ele. Me/lazy thread security/DCL/static internal class/Enumeration

1. mona1
First, run the Code:

public class HungurySingleton{  private static final HungurySingleton mHungurySingleton=new HungurySingleton();  private HungurySingleton(){}  public static HungurySingleton getInstance(){       return mHungurySingleton;  }}

The code is relatively simple. First, declare a private constructor to ensure that other classes cannot directly construct instances of this class. Create a private instance in the class, and then create an external interface to obtain the instance.
Note:Make sure that the created private instance and the access interface must be static.
Disadvantages:Because it is static, the JVM virtual machine will be created whenever you need to use the Singleton,Delayed loading of instances is not allowed..
Optimization:Lazy mode.

2. Lazy Mode
First, run the Code:

Public class LazySingleton {private static LazySingleton mLazySingleton; private LazySingleton () {} public static LazySingleton getInstance () {// initialize if (mLazySingleton = null) during the first creation) {mLazySingleton = new LazySingleton ();} return mLazySingleton ;}}

As shown in the code above, we do not create an instance at the beginning, but create it only when the instance is used. This solves the disadvantages of the hungry Chinese mode. But I am familiar with Java multithreading and know that such implementation cannot guarantee that the instance is unique in the case of multithreading.
Disadvantages:The instance cannot be unique in the case of multi-thread concurrency.In multiple threads, the lazy mode is invalid.
Optimization:Lazy thread security mode.

3. Lazy thread security mode
First, the Code is as follows:

Public class LazySafeSingleton {private static LazySafeSingleton mLazySafeSingleton; private LazySingleton () {} public static LazySingleton getInstance () {// Synchronous Code block implementing synchronized (LazySingleton. class) {if (mLazySingleton = null) {mLazySafeSingleton = new LazySafeSingleton () ;}} return mLazySingleton ;}}
Public class variables {private static LazySafeSingleton variables; private LazySingleton () {}// declare the synchronized keyword in the method name public static synchronized LazySingleton getInstance () {if (mLazySingleton = null) {mLazySafeSingleton = new LazySafeSingleton () ;}return mLazySingleton ;}}

This ensures thread security.
Disadvantages:It has performance defects because the synchronized keyword is used.
Optimization:DCL Mode

4. DCL mode Singleton
Also known as the double check lock mechanism, first go to the Code:

Public class classes {private static LazySafeSingleton libraries; private LazySingleton () {} public static LazySingleton getInstance () {// implement the synchronization code block if (mLazySingleton = null) {synchronized (LazySingleton. class) {if (mLazySingleton = null) {mLazySafeSingleton = new LazySafeSingleton () ;}}return mLazySingleton ;}}

This mode uses synchronous block locking to solve the performance problem of the lazysingleton security mode. It checks whether mLazySingleton is empty twice.
Disadvantages:MLazySafeSingleton = new LazySafeSingleton (); using new to create an instance is not an atomic operation. (I don't know what an atomic operation is)
The logic of this Code is: the first step is to allocate memory to the instance, and the second step is to use the New keyword to call the constructor to instantiate our object, step 3: point the image to the allocated memory space. However, our JVM virtual machines have optimized Command Re-sorting. What does this mean? These three steps may not be executed in the order of one, two, or three. At this time, the thread is not secure and an error is reported.
Solution: Set the instance variable to volatile.

private static volatile LazySafeSingleton mLazySafeSingleton;

Volatile can disable Optimization of JVM Command Re-sorting.

5. static internal class mode Singleton
First, run the Code:

Public class StaticInnerSingleton {private StaticInnerSingleton () {} public static StaticInnerSingleton getInstance () {return Holder. mStaticInnerSingleton;} // static internal class private static class Holder {private static final StaticInnerSingleton mStaticInnerSingleton = new StaticInnerSingleton ();}}

JVM provides synchronization control: static and final. Their modified variables have thread-safe features. Create an instance in the internal class. As long as we do not use this internal class, this internal class will not be loaded and the instance we need will not be created. Only when we call the getInstance () method for the first time will we load the internal class and initialize the class object. This ensures thread security and class uniqueness.

This method is recommended for creating the singleton mode.
Advantage: Use the uniqueness of static variables in the class.

The JVM mechanism ensures the thread security. We didn't use the synchronized keyword to improve our performance. Holder is private. Except the getInstance () method, there are no other external methods for access.

6. Enumeration
First, run the Code:

Public enum EnumSingleton {INSTANCE; // defines an enumeration unit, which is an INSTANCE public void doSomething (){...}}

The code is less in the form of static internal classes. This is a big advantage.
Of course, you can add some instances or some instance methods here. However, when there is only one enumeration unit, this instance is thread-safe. If other instances are added, they must be thread-safe.
Advantages:The code is easy to write.

The above is all the expressions of all Singleton instances.

Summary:
Ele. Me: Unable to delay loading instance
Lazy: the uniqueness of instances cannot be guaranteed under multi-thread concurrency.
Lazy thread security: Performance defects caused by synchronized keywords
DCL: Command Re-sorting by JVM Compiler
Static internal class/enumeration: delayed loading, thread security, and performance advantages

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.