Design Mode Reading Notes-single-piece Mode

Source: Internet
Author: User

Single-piece mode-ensure that a class has only one instance and there is only one entry point globally.
Class:
Public class Singleton {
Private static Singleton uniqueInstance;
// Other useful instance variables here
Private Singleton (){}
Public static Singleton getInstance (){
If (uniqueInstance = null ){
UniqueInstance = new Singleton ();
}
Return uniqueInstance;
}
// Other useful methods here
}
The single-piece mode mainly solves the problems where some resources in the entire program are shared, such as printers.
Problem: Solve the Problem of multithreading:
Three methods to solve the thread:
1. Use the synchronization method
Public Static synchronized myClass getInstance ()
{
Retuan new myClass ();
};
However, synchronizing a method may cause a program to be 100 times more efficient. If the efficiency is not a problem, you can.
Otherwise
2. Use "eager" to create an instance
Create Private static myClass instance = new myClass ();
3 "double check lock" (Java 5 or above supports the volatile keyword)
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;
}
}
Therefore, the unit price mode is very simple. In practice, public resources are often defined. Pay attention to multithreading.
This article is from the "Qingfeng" blog

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.