1. The classical realization of the single piece mode
Publicclass Singleton
{
private static singletonuniqueinstance;
Private Singleton () {} public
static Singleton getinstance ()
{
if (uniqueinstance = = null)
Uniqueinstance = Newsingleton ();
Return uniqueinstance
}
}
2. Define a single piece mode
Single-piece mode ensures that a class has only one instance and provides a global access point.
The design of a class as a separate instance of their own management, to avoid other classes to generate their own instances, only through a single piece of class to get a single instance
Provides a global access point to the instance, and when an instance is needed, queries to the class and returns a single instance.
Class Diagram:
3. Handle Multithreading
L use a thread lock
Publicclass Singleton
{
private static Singleton uniqueinstance;
private static Object obj = new Object ();
Private Singleton () {} public
static Singleton getinstance ()
{
if (uniqueinstance = = null)
{
Lock ( obj)
{
if (uniqueinstance = null)
uniqueinstance = new Singleton ();
}
}
Return uniqueinstance
}
}
L Create an instance using "eagerly" without delaying the instantiation
public class Singleton
{
private Staticsingleton uniqueinstance new Singleton ()//Create a single piece
in a static initializer Private Singleton () {} public
static Singleton getinstance ()
{return
uniqueinstance;
}
}
4. Summary
L single-piece mode ensures that there is at most one instance of a class in a program.
The L-piece mode also provides a global point to access this instance.
• Identify constraints on performance and resources, and be careful to choose the appropriate solution to implement a single piece to solve multithreaded problems.