Design Pattern series-singleton

Source: Internet
Author: User

I. Class Diagram

 

Ii. Intention

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

Iii. Applicability

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

B) when this unique instance should be extensible through subclass, and the customer should not need to changeCodeYou can use an extended instance.

IV. Implementation Method

1. Lazy Mode

 Package Effece. Singleton;

// Lazy Mode
// It is not initialized until the first call.
Public Class Singleton1 {
Private Static Singleton1 instance = Null ;

Private Singleton1 (){
}

Public Static Synchronized Singleton1 getinstance (){
If (Instance = Null ){
Instance =New Singleton1 ();
}
Return Instance;
}
}

2. Hunger Mode

PackageEffece. Singleton;
//Hunger mode,
//Initial Plan upon declaration
Public ClassSingleton2 {
Private StaticSingleton2 instace =NewSingleton2 ();

PrivateSingleton2 (){
}

Public StaticSingleton2 getinstance (){
ReturnInstace;
}
}

3. Double Check Mode

 Package Effece. Singleton;
// Double Check Mode
// Not secure: Http://www.ibm.com/developerworks/cn/java/j-dcl.html
Public Class Singleton3 {
Private Static Volatile Singleton3 instance = Null ;

Private Singleton3 (){}

Public Static Singleton3 getinstance (){
If (Instance = Null ){
Synchronized (Singleton3. Class ){
If (Instance = Null ){
Instance = New Singleton3 ();
}
}
}
Return Instance;
}
}

5. RuntimeClass Singleton Mode

 
Public ClassRuntime {
Private StaticRuntime currentruntime =NewRuntime ();

Public StaticRuntime getruntime (){
ReturnCurrentruntime;
}

Not explained: clear at a glance.

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.