What does it mean to install something in INSTANCE and not create a new object?

I was reading some code somewhere on the internet and I saw this interesting piece that intrigued me and I am curious how it works.

There is a ResourceManager class and looks like this:

public class ResourceManager {
  private static final ResourceManager INSTANCE = new ResourceManager();

  public static ResourceManager getInstance() {

      return INSTANCE;
  }

}

      

(It has a bunch of other things, but I don't think it needs to be included). However, what I'm interested in is that the author hasn't included a constructor. In fact, in his main method, he only makes a reference to that class and instead of creating a new object, he simply writes:

ResourceManager.getInstance().etc();

      

I have never seen such an encoding before. I had to change it because I needed a ResourceManager object to work, so I did this:

ResourceManager res = ResourceManager.getInstance();

      

Which worked great. However, I still don't quite understand what's going on here. How is this class created without a constructor?

+3


source to share


3 answers


This is a singleton pattern , which means there is only one instance of the class ResourceManager

(a constructor must actually be private

in order to ensure this).

However, I still don't quite understand what's going on here. How is this class created without a constructor?



If you don't explicitly write a constructor, Java will automatically add a default constructor (assuming the superclass also has a default constructor).

+8


source


To answer the question about no constructor:

All java classes that do not have a specific constructor have an implicit public no-args constructor.



However, a private no-args constructor must exist because this class is clearly designed to be singleton. But without a private constructor, you can create a new instance at any time.

+1


source


In Java, a class has a default constructor, assuming you do not provide a constructor. Otherwise it looks like the Singleton Pattern , from the Wikipedia link, a design pattern that restricts instantiation of a single object. Again, to make it correct Singleton

you should probably add a constructorprivate

private ResourceManager() {
  super();
}

      

Otherwise, someone can create it.

0


source







All Articles