Java and mode Singleton Mode

Source: Internet
Author: User

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.

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.