I want to create only one object of an class and reuse the same object over and over again. Is there any efficient way to do this.
How can I do this?
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.
A feature of Java that makes it an extremely useful language is the ability to reuse objects.
No, it's fine. Just create an array (or List ) of Player and extract the code of Player creation in a separate method.
In java you cannot create a method outside of a class. All methods must be encapsulated within a class. Therefore the main method as an entry point to the program must be within a class. When you run this program the main method will be run once and will execute the code inside it.
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;
}
}
This is generally implemented with the Singleton pattern but the situations where it is actually required are quite rare and this is not an innocuous decision.
You should consider alternative solutions before making a decision.
This other post about why static variables can be evil is also an interesting read (a singleton is a static variable).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With