1

Basically I have a class which an instance of is created via a Singleton class. The class should never been instantiated via any other means than the singleton class. My question is can the class be effectively 'not seen' by other classes, apart from Singleton.

I know inner classes and different pacakages etc would help, but I'm curious to see if anyone has a nice solution to this.

Thanks for replies

Ash
  • 3,494
  • 12
  • 35
  • 42

5 Answers5

2

Just refactor class itself as singleton. Private constructor and etc.

Vadim Ponomarev
  • 1,346
  • 9
  • 15
1

Java has no "friend" concept like C++

You mentioned nested classes (real inner classes will not work because they need the outer) and packages.

Other approaches to protected other classes but one from creating an instance are not known to me.

But in general there is no reason to build a singleton by an helper class.

You could build singleton using enums or static final vars

What is the best approach for using an Enum as a singleton in Java?

public enum Elvis implements HasAge {
    INSTANCE;
    private int age;

    @Override
    public int getAge() {
        return age;
    }
}

class X {
     public static final X instance = new X ();

     private X () {
     }
     ...
}  
Community
  • 1
  • 1
stefan bachert
  • 9,413
  • 4
  • 33
  • 40
1

In a sample scenario, using your API, do I need to declare?:

ToBeInvisibleClass instance = TheSingleton.getThatInvisibleInstnace();

If the answer is Yes, then the answer to your question is No since I need to declare a variable and for that I need the type to visible. If the answer is No, then using inner/nested class seems to be a proper approach or making the class itself the singleton.

nobeh
  • 9,784
  • 10
  • 49
  • 66
1

An easy and efficient way to do Singleton with an Enum:

public enum Singleton {
        INSTANCE;
        public void execute (String arg) {
            //... perform operation here ...
        }
}
Charles Menguy
  • 40,830
  • 17
  • 95
  • 117
1

To assure that instantiation only occurs through your class method, you can do the following:

  • Make the default constructor private
  • Save your singleton instance in a private method
  • Use a public static method to provide the instance to the clients:

In this site there's a nice example:

public class MySingleton { 
    private static MySingleton _instance = new MySingleton(); 

     private MySingleton() { 
        // construct object . . . 
    } 

    public static MySingleton getInstance() { 
        return _instance; 
    } 
Carlos Gavidia-Calderon
  • 7,145
  • 9
  • 34
  • 59