Java – create only one object for the class and reuse the same object
•
Java
I want to create only one object of a class and reuse the same object over and over again
How can I do this?
Solution
public final class MySingleton {
public final class MySingleton {
private static volatile MySingleton instance;
private MySingleton() {
// TODO: Initialize
// ...
}
/**
* Get the only instance of this class.
*
* @return the single instance.
*/
public static MySingleton getInstance() {
if (instance == null) {
synchronized (MySingleton.class) {
if (instance == null) {
instance = new MySingleton();
}
}
}
return instance;
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
