Single-Case mode

Source: Internet
Author: User

Single-Case mode

Singleton mode (Singleton pattern) is one of the simplest design patterns in Java. This type of design pattern belongs to the Create pattern, which provides an optimal way to create an object.

This pattern involves a single class that is responsible for creating its own objects, while ensuring that only a single object is created. This class provides a way to access its only object, which can be accessed directly without instantiating an object of that class.

Attention:

    • 1, the Singleton class can have only one instance.
    • 2, the Singleton class must create its own unique instance.
    • 3. The Singleton class must provide this instance to all other objects.

Introduced

Intent: Ensure that a class has only one instance and provides a global access point to access it.

Primary Solution: A globally used class is frequently created and destroyed.

When to use: when you want to control the number of instances, save system resources.

How to Solve: determine if the system already has this singleton, if there is a return, if not created.

Key code: The constructor is private.

Application Example: 1. A party can only have one chairman. 2, Windows is multi-process multithreading, in the operation of a file, it is inevitable that multiple processes or threads simultaneously manipulate a file, so all files must be processed through a unique instance. 3, some Device Manager is often designed as a single-case mode, such as a computer has two printers, in the output will be processed can not be two printers to print the same file.

Advantages: 1, there is only one instance in memory, reduce the memory overhead, especially the frequent creation and destruction of instances (such as the management of the school home page cache). 2, avoid the multiple occupation of resources (such as write file operations).

Cons: no interface, no inheritance, conflict with a single responsibility principle, a class should only care about internal logic, not how to instantiate outside.

usage Scenario: 1, requires the production of a unique serial number. 2, the counter in the WEB, do not have each refresh in the database Riga once, with a single case first cache up. 3, the creation of an object needs to consume too much resources, such as I/O and database connection.

Note:the getinstance () method requires the use of synchronous lock synchronized (Singleton.class) to prevent multi-threaded simultaneous entry resulting in instance being instantiated multiple times.

Realize

We will create a Singleobject class. The Singleobject class has its own private constructor and a static instance of itself.

The Singleobject class provides a static method for the outside world to obtain a static instance of it. Singletonpatterndemo, our demo class uses the Singleobject class to get the singleobject object.

Step 1

Create a Singleton class.

Singleobject.java

 Public classSingleobject {//create an object of Singleobject   Private StaticSingleobject instance =NewSingleobject (); //let the constructor be private so that the class is not instantiated   PrivateSingleobject () {}//get the only available objects    Public StaticSingleobject getinstance () {returninstance; }    Public voidShowMessage () {System.out.println ("Hello world!"); }}

Step 2

Gets the unique object from the Singleton class.

Singletonpatterndemo.java

 Public classSingletonpatterndemo { Public Static voidMain (string[] args) {//Illegal Constructors//compile-time error: Constructor Singleobject () is not visible//Singleobject object = new Singleobject (); //get the only available objectsSingleobject Object =singleobject.getinstance (); //displaying MessagesObject.showmessage (); }}

Step 3

Verify the output.

Hello world!
Several implementation modes of single case pattern

There are several ways to implement a singleton pattern, as follows:

1, lazy-type, thread unsafe

whether Lazy initialization: Yes

whether multithreading security: No

difficulty to achieve: easy

Description: This approach is the most basic implementation, this implementation of the biggest problem is not support multithreading. Because there is no lock synchronized, it is strictly not a single case mode.
This way the lazy loading is obvious, does not require thread safety, and the multithreading does not work correctly.

code example:

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

Several of the implementations described next support multithreading, but differ in performance.

2, lazy, thread-safe

whether Lazy initialization: Yes

whether multithreading security: Yes

difficulty to achieve: easy

Description: This approach has good lazy loading and can work well in multi-threading, but it is inefficient and does not require synchronization in 99% cases.
Advantage: The first call is initialized to avoid memory waste.
Disadvantage: Must lock the synchronized to guarantee the single case, but the lock will affect the efficiency.
The performance of getinstance () is not critical to the application (this method is used infrequently).

code example:

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

3. A hungry man type

whether Lazy initialization: No

whether multithreading security: Yes

difficulty to achieve: easy

Description: This method is more commonly used, but it is easy to produce garbage objects.
Advantages: Without locking, execution efficiency will increase.
Disadvantage: The class loads when it initializes, wasting memory.
It avoids the synchronization problem of multithreading based on classloder mechanism, however, instance is instantiated when class is loaded, although there are many reasons for class loading, most of them call getinstance method in singleton mode. However, it is not certain that there are other ways (or other static methods) that cause the class to load, when initializing instance obviously does not achieve the effect of lazy loading.

code example:

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

4. Double check lock/double check lock (DCL, ie double-checked locking)

JDK Version: From JDK1.5

whether Lazy initialization: Yes

whether multithreading security: Yes

difficult to achieve: more complex

Description: This approach uses a dual-lock mechanism to maintain high performance in a secure and multi-threaded environment.
The performance of getinstance () is critical to the application.

code example:

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

5. Registered/Static internal class

whether Lazy initialization: Yes

whether multithreading security: Yes

Implementation difficulty: General

Description: This method can achieve the same effect as double lock mode, but it is easier to achieve. Using lazy initialization for a static domain should be used in this manner instead of double-lock mode. This approach applies only to static domains, and the double-lock method can be used when the instance domain requires lazy initialization.
This approach also takes advantage of the classloder mechanism to ensure that there is only one thread initialized instance, which is different from the 3rd way: the 3rd way, as long as the Singleton class is loaded, then the instance is instantiated (not reaching the lazy Loadin g effect), which is Singleton class is loaded, instance not necessarily initialized. Because the Singletonholder class is not actively used, the load Singletonholder class is displayed only if it is displayed by calling the GetInstance method, thus instantiating the instance. Imagine if instantiating instance is consuming resources, so you want it to delay loading, and on the other hand, do not want to instantiate when the Singleton class is loaded, because there is no way to ensure that the Singleton class may be actively used in other places to be loaded, then this time instantiate The instance is obviously inappropriate. At this time, this approach is reasonable compared to the 3rd way.

code example:

 Public classSingleton {Private Static classSingletonholder {Private Static FinalSingleton INSTANCE =NewSingleton (); }      PrivateSingleton () {} Public Static FinalSingleton getinstance () {returnsingletonholder.instance; }  }  

6. Enumeration

JDK Version: From JDK1.5

whether Lazy initialization: No

whether multithreading security: Yes

difficulty to achieve: easy

Description: This implementation has not been widely used, but this is the best way to implement a singleton pattern. It is more concise, automatically supports serialization mechanisms, and absolutely prevents multiple instantiations.
This approach is advocated by effective Java author Josh Bloch, which not only avoids multithreading synchronization problems, but also automatically supports serialization mechanisms, prevents deserialization from recreating new objects, and absolutely prevents multiple instantiations. However, because of the JDK1.5 after the inclusion of the Enum feature, in this way can not be used to write people feel unfamiliar, in the actual work, but also very little use.
Private construction methods cannot be called by reflection attack.

code example:

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

Rule of Thumb: in general, the 1th and 2nd lazy methods are not recommended, and the 3rd method of a hungry man is recommended. The 5th method of registration is used only if you want to explicitly implement the lazy loading effect. If you are involved in deserializing the creation of an object, you can attempt to use the 6th enumeration method. If there are other special requirements, consider using the 4th type of double lock mode.

Single-Case mode

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.