Concept:
Ensure that a class has only one instance and provides a global access point to it.
In the past, we used to set a global variable so that an object can be accessed. But it cannot prevent multiple objects in your instance. In this case, the class itself is responsible for saving its unique instance. This class ensures that no other instance can be created and provides a method to access the instance.
As described above, the singleton mode has the following features:
1. A singleton class can only have one instance.
2. The Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to all other objects.
Therefore, the specific method (element) for creating an instance of a class is:
1. Private and static member variables
2. Private Constructor
3. A public and static portal Method
Based on the specific method above, let's look atCode
Public class test {Private Static Test instance = new test (); Private test () {}public static test getinstance () {return instance ;}}
From the code above, we can see that when the class is loaded to the memory, an instance object has been created in the memory before we call the getinstance () method. That is to say, whether or not I want to use this method, the Instance Object already exists in the memory. At this time, this object is a redundant object, which will occupy memory resources. Therefore, we call this Singleton mode the "Hungry Chinese" Singleton mode. It is actually a "pre-loading" process.
The "lazy" Singleton mode (that is, the "delayed" Object creation) creates this object only when we need it. This avoids the memory resources occupied by creating objects in advance.
Public class test {Private Static Test instance = NULL; private test () {} public static test getinstance () {If (instance = NULL) then {instance = new test ();} return instance ;}}
However, by observing the above code, we can see that there are still some problems. Assume that multiple processes call the getinstance () method at the same time, so that multiple objects may be created simultaneously, which is not the singleton mode. Therefore, we can add the "Synchronize" keyword to make our code more rigorous. After improvement
Public class test {Private Static Test instance = NULL; private test () {} public static synchronized test getinstance () {If (instance = NULL) then {instance = new test ();} return instance ;}}