The Java Singleton mode is used to ensure that a class is only instantiated once, that is, only one corresponding object exists. In a web program we will use a core-assigned servlet program, here we can use this design pattern.
General Singleton mode usually has several forms:
The first form: Define a class, its constructor is private, it has a type of PRIVATE for a Static, an instantimeter of the class initialization, get a reference to it through a public GetInstance method, then call it Methods.
Public class singleton {
Private kindleton () {}
// Is it very strange to define an instance inside yourself?
// Note this is Private only for internal calls
Private static singleleton instance = new singleleton ();
/ / Here is a static method for accessing this Class, you can directly access
Public static singleleton getinstance () {
Return Instance;
}
}
The second form:
Public class singleton {
Private static singleton instance = null;
Public static synchronized singleton getInstance () {
// This method has been improved above, and it is only the first time.
// Generate an instance when using it, improve efficiency!
IF (instance == null)
Instance = new singleleton ();
Return Instance;}
}
Other forms:
Define a class, its constructor is private, all methods are static.
It is generally considered that the first form is more secure.