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