[java] Singleton pattern in Java

Started by
24 comments, last by Zahlman 18 years, 10 months ago
Ok, say you have a thingy like the below code.

public class SingletonObject
{
    private SingletonObject()
    {
    }

    public static synchronized SingletonObject getSingletonObject()
    {
      if (ref == null)
          ref = new SingletonObject();
      return ref;
    }

    private static SingletonObject ref;
    //other stuff

    //Note this method -- esp. the static here
    public static void add(whateverObj whatever) {
      //do something
    }
}



It seems to me that there's two ways to use a class like this--only one is correct. SingletonObject.add(whatever); SingletonObject.getSingletonObject().add(whatever); Would it be correct to say that this part SHOULD NOT be static? public static void add(whateverObj whatever) Otherwise you can access the singleton object before it's instantiated. Without the static you can only call this: SingletonObject.getSingletonObject().add(whatever); Which should always be safe... Can anyone verify that this is all correct?
Advertisement
I'm pretty sure it's not supposed to be static.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                          
Looking for video game music? Check out some of my samples at http://www.youtube.c...ser/cminortunes            
                                                          
I'm currently looking to create music for a project, if you are interested e-mail me at cminortunes@gmail.com    
                                                          
Please only message me for hobby projects, I am not looking to create music for anything serious.
The method is not supposed to be static, that defeats the whole purpose of the pattern actually. You should be using the getSingletonObject()
Thanks for confirming that, makes sense.
Hi,

The add() method must not be static. Also, to ensure you really have a singleton, you could use a static inner class, like this:

public final class Singleton {  private static final class SingletonHolder {    private static final Singleton singleton = new Singleton();  }  private Singleton() {    // Singleton instantiation  }  private static final Singleton getInstance() {    return SingletonHolder.singleton;  }  public final void add(Object obj) {    // method of the Singleton  }}


However, you used a synchronized approach, so I'm not certain about how it should behave.

Son Of Cain

Edit: [ fixed the source tag ]
a.k.a javabeats at yahoo.ca
For games, do not use synchronized unless you feel very unsafe.
If you feel very unsafe, then you need to redesign in the first place :)

At any rate, remember that synchronized methods will KILL your fps if used at inopportune times. They're best left for server commands and other things that arn't FPS dependent.
Well,

1) This is server code
2) FPS? hehe...in strategy wargaming it's not that important! :)

but thanks for the feedback.
Are you sure you need an instance of the singleton or are you doing that simply to say "I have implemented the Singleton Pattern"? Wouldn't a class with all static data and methods be enough?

Son of Cain: I'm not seeing any benefit to simply having a
private static final Singleton singleton = new Singleton();

in there. I'm not completely sure when inner classes are exactly loaded (when their container class is loaded or when they are first accessed?) but if the initialization time is important I'd rather set it to null during initialization and create it in getSingleton() or a more specific initialization method...
The use of inner classes to hold Singleton instances is only necessary when you have to ensure a Singleton is created outside the scope of the class providing the instance, but still in the same source file.

It is a bit intrinsic and very specific, but the inner class acts like a factory for the singleton instance. It is only interesting when you have an hierarchy of singletons, like: EquipmentFactory <- WeaponFactory, ArmorFactory, where all of them are singletons.

Son Of Cain
a.k.a javabeats at yahoo.ca
Quote:Original post by BitMaster
Are you sure you need an instance of the singleton or are you doing that simply to say "I have implemented the Singleton Pattern"? Wouldn't a class with all static data and methods be enough?


Actually I had the same question myself earlier. I have a few guesses as to the answers, but rather than throwing stuff out I'll wait for someone more enlightened in Java to illustrate why this is better.

I suspect it has mostly to do with future changes: "if you decide that the class should no longer be a singleton, you may simply change the implementation of getInstance."

This topic is closed to new replies.

Advertisement