Create only one object for the class and reuse the same object

I want to create only one class object and reuse the same object over and over again. Is there an effective way to do this.

How can i do this?

+7
source share
8 answers
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; } } 
+9
source

This is usually implemented using the Singleton pattern , but situations where it is really necessary are quite rare, and this is not a harmless solution.

Before making a decision, you should consider alternative solutions .

This is another post about why static variables can be evil - also an interesting read (singleton is a static variable).

+2
source

The easiest way to create a class with a single instance is to use enum

 public enum Singleton { INSTANCE } 

You can compare this with Steve Taylor's answer to find out how simple it is than alternatives.

By the way: I would suggest that you use solitary stateless singles. If you need single, single versions, you'd better use dependency injection.

+1
source

This will be the Singleton template - basically, you prevent the build using a private constructor and "get" an instance with a static synchronized receiver, which will create one instance if it does not already exist.

Greetings

0
source

There is a design template called Singleton. If you implement it, you will get what you need.

Take a look at this one to see various ways to implement it.

0
source

You are looking for the Singleton template . Read the wikipedia article and you will find examples of how it can be implemented in Java.

Perhaps you would also like to know more about Design Patterns, then I suggest you read the book “Head First Design Patterns” or the original book of design patterns by Erich Gamma and others (the former contains Java examples, the latter does not work)

0
source

Yes. It is called the Singleton class. You create one instance and use it in all your code.

0
source

What you are looking for is a Singleton Pattern .

0
source

All Articles