Creation Mode (5): Singleton (Singleton Mode)

Source: Internet
Author: User

Singleton mode ensures that a class has only one instance, and the instance Singleton mode is self-instantiated and provided to the entire system. The Singleton mode can only be used when there is a real "Single Instance" demand.

 1   Class Singleton {
2 Private Static Singleton sing;
3
4 Private Singleton (){
5 }
6
7 Public Static Singleton getinstance (){
8 If (Sing = Null ){
9 Sing = New Singleton ();
10 }
11 Return Sing;
12 }
13 }
14
15 Public Class Test {
16 Public Static Void Main (string [] ARGs ){
17 Singleton sing = singleton. getinstance ();
18 Singleton sing2 = singleton. getinstance ();
19 System. Out. println (SING );
20 System. Out. println (sing2 );
21 }
22 }

However, this Singleton mode seems to have some problems. In the case of multi-thread concurrency, there may still be two Singleton cases in the IF (sing = NULL) judgment, to avoid this, you 'd better change it:

1 ClassSingleton {
2PrivateSingleton (){}
3Private StaticSingleton sing =NewSingleton ();
4Public StaticSingleton getinstance (){
5ReturnSing;
6}
7}

There is also a singleton ~

Use enumeration:

EnumSingleton {
Sing;
//Method
Public VoidTest (){
System. Out. println ("Singleton ");
}
}

Because each enumeration is a singleton by default

 

Thought it was over? No ~ Use static internal classes:

ClassSingleton {
Private Static ClassSingletoninner {
Private StaticSingleton sing =NewSingleton ();
}
PrivateSingleton (){}
Public StaticSingleton getinstance (){
ReturnSingletoninner. Sing;
}
}

The advantage of this is that you can call the internal class to create this Singleton only when the class is not created during loading.

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.