Ajay Gopal Shrestha
Ajay Gopal Shrestha

Reputation: 199

Create only one object for a class and reuse same object

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

Answers (8)

Peter Lawrey
Peter Lawrey

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

assylias
assylias

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

Steve
Steve

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

Jean Logeart
Jean Logeart

Reputation: 53829

What you are looking for is the Singleton Pattern.

Upvotes: 0

giorashc
giorashc

Reputation: 13713

Yes. Its called a Singleton class. You create one and only instance and use it throughout your code.

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

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

Dan D.
Dan D.

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

Anders R. Bystrup
Anders R. Bystrup

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

Related Questions