Singleton mode ensures that a class has only one instance, and the instance is instantiated and provided to the entire system.
Hungry Chinese Singleton type
Code
Public class EagerSingleton
{
Private static final EagerSingleton m_instance =
New EagerSingleton ();
/**
* Private default constructor
*/
Private EagerSingleton (){}
/**
* Static factory Method
*/
Public static EagerSingleton getInstance ()
{
Return m_instance;
}
}
When the class is loaded, the static variable m_instance is initialized, and the private constructor of the class is called.
Lazy Singleton type
Public class LazySingleton {
Private static LazySingleton m_instance;
/**
* Private default constructor, which ensures that external entities cannot be directly instantiated
*/
Private LazySingleton (){}
/**
* The static factory method returns a unique instance of this class.
*/
Synchronized public static LazySingleton
GetInstance (){
If (m_instance = null ){
M_instance = new LazySingleton ();
}
Return m_instance;
}
}
Unlike the hunger-style Singleton, the lazy Singleton initializes itself when it is called for the first time. In the lazy implementation, synchronization (synchronized keyword) is used for static factory methods to process multi-threaded environments.
From the perspective of resource utilization, the lazy style is slightly better; from the perspective of speed and reflection time, the hungry style is better.
Ele. Me Khan Singleton class can be implemented in java, but it is not easy to implement in c ++, because static initialization does not have a fixed sequence in c ++, that is, the initialization of the static variable m_instance and the loading sequence of the class are not guaranteed, and problems may occur. This is why the example is lazy when GoF introduces the concept of Singleton. In fact, this book thinks that the ELE. me sweat Singleton class is more in line with the characteristics of the java language itself.