-1

is it possible to access "get methods" of other classes if we import the package that contains other classes to "singleton class"? If its not possible how do I do this. My intention is to grab "get methods" of other classes through singleton class

public class Singleton {

private static Singleton st = null;

private Singleton() {

}

public static Singleton getInstance() {
    if (st == null) {
        st = new Singleton();
    }
    return st;

}

}
  • Your code doesn't compile, and isn't trying to access any "get methods". Please come up with an example which illustrates what you are trying to do. – tgdavies Apr 29 '21 at 23:01
  • It's possible to use getter methods from other classes, if programmed. You'd have to do this carefully if you wish to stick to the philosophy of the Singleton Pattern. – NomadMaker Apr 29 '21 at 23:07
  • @tgdavies, I'm acutally lost and not sure how to get instance from singleton class. I have 3 classes. "my account, my products, purchase history,". I want to get those classes get methods through singleton class. this is what I'm trying to do. – Joseph Martínez Apr 29 '21 at 23:07
  • @NomadMaker , does that mean I should define get methods in singleton class ? all these "my account, my products, purchase history," have get methods. – Joseph Martínez Apr 29 '21 at 23:09
  • Since your question doesn't explain what you want to do, how can I advise you on anything like that? I don't think that a singleton should be dealing with "my account", though. – NomadMaker Apr 29 '21 at 23:11

1 Answers1

1

Your code is a bit confusing. It will never compile, as that sc instance is a DataCenter, whereas the Singleton class is a total different type. In fact, it is not even its subtype.
However, let me explain something in general about what you are trying to achieve.

By definition, the Singleton pattern intends to realize one single instance of a certain class for the whole program lifecycle, which you can obtain by invoking the getInstance method.

Normally, it is the same class that you want to make Singleton that hides its contructor (by making it private) and make getInstance method public, along with other utility methods.

If you want to use another class to make another one Singleton, I can actually recon a different design pattern. Personally, I have never seen a Singleton of singletons. Perhaps you are referring to a Factory method pattern, but I suggest that you look into its implementation carefully.

This link should answer your question: Examples of GoF Design Patterns in Java's core libraries.

Marco Tizzano
  • 1,726
  • 1
  • 11
  • 18