Singleton with generics - howto?

Which is the best way to use generics to write an abstract base class or an Interface for a Singleton?

I’ve many lazy created singletons in my code. Lazy means they create themself when the first user class declares the singleton class. It looks like this:


public class TheSingelton 
{
  private static TheSingelton sInstance = new TheSingelton();

  private TheSingelton()
  {}

  public static TheSingelton getInstance()  {
    return sInstance;
  }

The con is that for every class which wants to be a Singleton it has to double these lines with its own type.
In C++ I used to use templates for these kind of things. I guess with generics we finally can have a real Singleton base abstract class or Interface in Java, too?
(I’d prefer an abstract class because even the sInstance shall be inside the base class, not in the derivate.)

http://www.weiqigao.com/blog/2004/07/27/1090981933000.html

That’s exactly the error I run into with my silly-dilly Tiger implementation of a Singleton. I’m still too much in C++ templates (which Java generics are not)…

Btw did you ever visit a Java house? Ie a restaurant with Javanese food. Excellent, I can say… :slight_smile:

another possibility is to not use inheritence/generics to abstract. the gang of four’s book “design pattern” usually recommends this method of abstraction. for example, you could have a singleton that can be used to register other instances as singletons. if you decide to register your singleton’s by type, then you are using the concepts of a “flattened” version of sun’s beancontext. if you register by string name then you have built a nameservice.