Singleton design model:Ensure that a class has only one instance and provides a global access point to it.
Objective: Singleton is a creation-based design model that mainly solves the problem of object creation.
Ensure that the class has only one function, that is, creating its own instance. Because there is only one global change point, that is, creating an object.
The following are instances in a single thread:
Public class Singleton {<br/> Public static Singleton instance = NULL; <br/> private Singleton () {</P> <p >}< br/> Public static Singleton getinstance () {<br/> If (instance = NULL) {<br/> instance = new Singleton (); <br/>}< br/> return instance; <br/>}< br/>}
Public class singletona {<br/> private singletona () {</P> <p >}< br/> static class singletonholder {<br/> static singletona instance = new singletona (); <br/>}</P> <p> Public static singletona getinstance () {<br/> return singletonholder. instance; <br/>}< br/> Public static void main (string [] ARGs) {<br/> singletona singlea = singletona. getinstance (); <br/> singletona singleb = singletona. getinstance (); <br/> system. out. println (singlea. hascode (); <br/> system. out. println (stringb. hascode (); <br/>}< br/>}
Multithreading
Public class singletonb {<br/> Public static singletonb instance = NULL; <br/> Public synchronized static singletonb getinstance () {<br/> If (instance = NULL) {<br/> instance = new singletonb (); <br/>}< br/> return instance; <br/>}< br/> private singletonb () {</P> <p >}< br/>}
Main Purpose: database connection/user group type/