0

I frequently setup singleton classes that are intended to be used by other programmers and I find that I'm not sure if there is a preferred way to setup access to methods in those classes. The two ways I've thought to do it are:

public class MyClass {
    private static MyClass instance;

    public static void DoStuff( ) {
        instance.DoStuffInstance( );
    }

    private void DoStuffInstance( ) {
        // Stuff happens here...
    }
}

where the usage is: MyClass.DoStuff( );

or something more like this:

public class MyClass {
    public static MyClass instance;

    public void DoStuff( ) {
        // Stuff happens here...
    }
}

where the usage is: MyClass.instance.DoStuff( );

Personally, I tend to prefer the first option. I find that having MyClass.instance all over the place is both ugly and unintuitive to remember for less experienced programmers.

Is there any good reason to prefer one of these over the other? Opinions are fine. Just curious what others think.

casimps1
  • 1,749
  • 1
  • 11
  • 8
  • see http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java The best way to do it is by using an enum. – Pierre-Henri Nov 01 '12 at 14:49

1 Answers1

0

I've never seen a Singleton implemented this way. A typical setup might be something like this:

public class MyClass {

    private static final MyClass instance = null;

    // Private to ensure that no other instances can be allocated.
    private MyClass() {}

    // Not thread safe!
    public static MyClass getInstance() {
        if( instance == null ) {
            instance = new MyClass();
        }
        return instance;
    }

    public void DoStuff( ) {
        // Stuff happens here...
    }
}

This way all of the calls will be similar to instance.DoStuff(); and you will only need to define one method per "operation", rather than needing a static method and then the actual "instance" method that your first approach uses.

Also, the way you have it set up, it looks like you can call those static methods before the instance is actually initialized, which is a problem.

Nick Hartung
  • 418
  • 3
  • 13