Reputation: 199
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?
Upvotes: 9
Views: 19406
Reputation: 533530
The simplest way to create a class with one one instance is to use an enum
public enum Singleton {
INSTANCE
}
You can compare this with Steve Taylor's answer to see how much simple it is than alternatives.
BTW: I would only suggest you use stateless singletons. If you want stateful singletons you are better off using dependency injection.
Upvotes: 2
Reputation: 328618
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).
Upvotes: 2
Reputation: 8809
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;
}
}
Upvotes: 11
Reputation: 13713
Yes. Its called a Singleton class. You create one and only instance and use it throughout your code.
Upvotes: 0
Reputation: 298898
You are looking for the Singleton pattern. Read the wikipedia article and you will find examples of how it can be implemented in Java.
Perhaps you'd also care to learn more about Design Patterns, then I'd suggest you read the book "Head First Design Patterns" or the original Design Patterns book by Erich Gamma et al (the former provides Java examples, the latter doesn't)
Upvotes: 0
Reputation: 32391
There is a design pattern called Singleton. If you implement it, you will get to what you need.
Take a look at this to see different ways to implement it.
Upvotes: 0
Reputation: 16060
That would be the Singleton pattern - basically you prevent construction with a private constructor and "get" the instance with a static synchronized getter that will create the single instance, if it doesn't exist already.
Cheers,
Upvotes: 0