Design Pattern --- Singleton pattern, design pattern --- Pattern

Source: Internet
Author: User

Design Pattern --- Singleton pattern, design pattern --- Pattern

In the world of design patterns, the singleton model may be the simplest. Although simple, it still needs to go through a little twists and turns if you want to thoroughly understand it.

Next, let's take a look:


In actual development, we only need one object, such as the thread pool, cache, dialog box, log object, and task manager. These objects can only have one instance. Multiple instances may cause many problems.


You may say why we don't need java global variables, which is convenient. Yes, but this method has some disadvantages. If we assign an object to a global variable, we must create an object at the beginning of the program. Once this object is very resource-consuming, the program has never been used in execution, so this is a waste.


In Singleton mode, to ensure that an object can only be instantiated once, let's look at a prototype code:

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

Here, we use a static variable to record the unique instance of the Singleton class and set the constructor to private. This constructor can be called only within the Singleton class. Then we use the getInstance () method to instantiate the object and return this instance. If the uniqueInstance is empty, it indicates that no instance has been created. If it is not empty, it indicates that an object has been created before, and the return Statement is skipped directly.


But if you think about it, you will find that the above Code has some problems. Where is the problem?


If we want to apply multithreading, if two or more threads want to execute the above Code, multiple instance objects may be generated, that is, there is no synchronization mechanism, if both threads run uniqueInstance = null, two objects will be generated, and the result is incorrect.


You may say that you add the synchronized keyword to the method. Yes, the following code is available:

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

In this way, we add the synchronized keyword to the getInstance () method, so that each thread waits for other threads to leave the method before entering this method. That is to say, no two threads can enter this method at the same time.


But what is the problem? Think about it. It is very simple:Synchronization reduces performance


That is to say, we only need to synchronize this method for the first time. Once the uniqueInstance variable is set, we no longer need to synchronize this method, because only the first unqueInstance = null, every time this method is called, synchronization is redundant and even cumbersome.


Therefore, sometimes it is necessary to flexibly respond to the situation.


If the performance of getInstance () is not very important to the application, do nothing, but you must know that, synchronizing a method may result in a 100-fold reduction in program execution efficiency, so many times we have to reconsider.


Of course, if we are sometimes eager to create an instance without delaying instantiation, we will create a singleton in the static initiator, as shown in the following code:

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

This code is thread-safe.


Next let's look at the final version of the singleton mode:

Double check locking, reduce the use of synchronization in getInstance:

Double-checked locking is used to check whether the instance has been created. If the instance has not been created, it is synchronized, this is exactly what we want:

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

The volatile keyword is used to notify other threads of variable update operations, to ensure that new values can be synchronized to the primary memory immediately, and to refresh from the primary memory immediately before each use. When the variable is declared as volatile, the compiler and runtime will notice that the variable is shared.

Here, the volatile keyword ensures that when the uniqueInstance variable is initialized to a Singleton instance, multiple threads can correctly process the uniqueInstance variable.

If performance is the focus of your relationship, this practice can help you greatly reduce the time consumption of getInstance.


What is the singleton design model?

Java mode Singleton mode:
Singleton mode ensures that a class has only one instance and provides the instance to the entire system.
Features:
1. One class can only have one instance
2. Create the instance by yourself.
3. The entire system uses this instance.
For example, in the following object diagram, there is a "singleton object ", "Customer A", "Customer B", and "customer C" are the three customer objects of the singleton object. As you can see, all customer objects share one singleton object. In addition, we can see from the singleton object to its own connection line that the singleton object holds a reference to itself.

The Singleton mode ensures that only one instance of a Class exists in a Java application. In many operations, such as creating a directory database connection, such single-threaded operations are required. Some resource managers are often designed to work in singleton mode.
External resources: for example, each computer may have several printers, but only one Printer Spooler can be used to prevent two print jobs from being output to the Printer at the same time. Each computer can have several communication ports. The system should centrally manage these communication ports to prevent a communication port from being called by both requests at the same time. For example, most software has one or more attribute files to store system configurations. Such a system should be managed by an object.

Example: Windows recycle bin.
In the entire Windows system, the recycle bin can only have one instance, and the entire system uses this unique instance, and the recycle bin provides its own instance. Therefore, the recycle bin is a singleton application.

Two forms:
1. Hunger type Singleton
Public class Singleton {

Private Singleton (){}

// Define your own instance internally. Isn't it strange?
// Note that this is private for internal calls only

Private static Singleton instance = new Singleton ();

// Here is a static method for external access to this class, which can be accessed directly.
Public static Singleton getInstance (){
Return instance;
}
}

2. Lazy Singleton type

Public class Singleton {

Private static Singleton instance = null;

Public static synchronized Singleton getInstance (){

// This method is better than above. You don't need to generate objects every time. It's just the first time.

// Generate instances during use, improving efficiency!
If (instance = null)
Instance = new Singleton ();
Return instance ;}

}

The second form is lazy initialization. That is to say, the initial Singleton is used for the first call and will not be regenerated in the future .... Remaining full text>

How does java Singleton mode (single design mode) ensure that only one instance can be generated? More specific explanation

I think this comment has been quite clear. The 23 Design Patterns of GOF are quite clear. For a Singleton, a Class has only one instance in a Classloader. If you write a private constructor in a class, you cannot create instances of this class except yourself. One static domain is your instance, NEW by myself, the static method that can be accessed by other classes only returns this instance, instead of New, so it is guaranteed that the second one cannot be created!

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.