Introduction to the singleton problem: some new objects are often used when we write programs, and these objects are used in the same sense. So every time we create a new object of this type, multiple objects with the same usage meaning exist in the memory. System resources are largely wasted. The Singleton mode ensures that only one instance of a class exists in a Java application. The specific implementation is divided into two forms: full and hungry Chinese: loaded by the class loader before use, and the code is implemented as follows (note that the constructor must overwrite into private, so that the object cannot be new externally)
Public ClassHungry {
Private StaticHungry
Hungry=
NewHungry ();
Private IntIndex = 0;
PrivateHungry (){}
Public StaticHungry getinstance (){
Return Hungry;}
Public IntGetindex () {index ++;
ReturnIndex ;}} this implementation method is usually used for counters, such as computing traffic. The disadvantage of this method is that the system loading is slow and exceptions cannot be captured. thread security problems may occur when the system concurrency is large. The full Chinese style can solve the above problem well: the full Chinese Style: delayed initialization, the object is instantiated when used for the first time. The code implementation is as follows:
Public ClassFull {
Private StaticFull
Full=
Null;
Private IntIndex = 0;
PrivateFull (){}
Public Static SynchronizedFull getinstance (){
If(
Full=
Null){
Try{
Full=
NewFull ();}
Catch(Exception e ){}}
Return Full;}
Public IntGetindex () {index ++;
ReturnIndex ;}} can be further evolved through the single-State mode, and the multi-state mode has emerged. Its implementation principle is the same as that of the single-State mode. It mainly emphasizes that there are only a few such object codes in the system:
Public ClassMultion {
Private StaticMultion
MT1=
Null;
Private StaticMultion
MT2=
Null;
Private IntIndex = 0;
PrivateMultion (){}
Public Static SynchronizedMultion getinstance1 (){
If(
MT1=
Null){
Try{
MT1=
NewMultion ();}
Catch(Exception e ){}}
Return MT1;}
Public Static SynchronizedMultion getinstance2 (){
If(
MT2=
Null){
Try{
MT2=
NewMultion ();}
Catch(Exception e ){}}
Return MT2;}
Public IntGetindex () {index ++;
ReturnIndex;} Note: This single State is for a JVM. If it is in a distributed system, it is not applicable. That is to say, it is best not to use a container-based application, it is unclear about the future deployment environment of the application.