A single state in Java
Single-State definition:
The main purpose of the Singleton mode is to ensure that only one instance of a class is present in a Java application.
Such a single-threaded operation is required in many operations, such as establishing a directory database connection.
Also, Singleton can be state; In this way, a plurality of single-state classes together can be as a state warehouse to provide services, for example, you want to the forum posts counter, each time you need to count, the single-state class can keep this count, and can synchronize security automatically plus 1, if you want to save this number to the database permanently, You can do it conveniently without modifying the single-state interface.
In addition, Singleton can be stateless. Provides tool-type functionality,
The Singleton model provides us with the possibility of this implementation. The advantage of using singleton is that it can save memory because it limits the number of instances and facilitates Java garbage collection (garbage collection).
We often see that the class loader in the Factory mode is also implemented in the singleton mode, because the loaded class is actually a resource.
How do I use it?
The general singleton pattern usually has several forms:
The first form of:
public class Singleton {
Private Singleton () {}
Is it strange to define an instance of yourself within yourself?
Note that this is private only for internal calls
Privatestatic Singleton instance = new Singleton ();
This provides a static method for external access to this class, which can be accessed directly
public static Singleton getinstance () {
return instance;
}
}
The second form of:
public class Singleton {
private static Singleton instance = NULL;
publicstaticsynchronized Singleton getinstance () {
This method is better than the above, and does not have to be generated every time, just the first time
Generate an instance when used, improve the efficiency!
if (instance==null)
Instance=new Singleton ();
return instance;
}
}
Use Singleton.getinstance () to access a single-state class.
The second form above is the lazy initialization, which means that the initial singleton is first invoked, and no more generation is needed.
Note that synchronized in the form of lazy initialization, this synchronized is important, if there is no synchronized, then using getinstance () is possible to get multiple singleton instances.
Java Single State