Karan Khanna
Karan Khanna

Reputation: 2137

Can a Singleton class be generic?

I want to have a rest client for my application. As Singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves. I thing the rest client should be implemented as a Singleton class.

Can I implement the class in a generic way so that I can somehow control the type of the object I want the methods of the class to return.

I am looking for something like:

public class JersyRestClient <T> implements RestClient
{
    private static JersyRestClient instance = null;

    private JersyRestClient()
    {

    }

    public static JersyRestClient getInstance()
    {
        if (instance == null)
        {
            synchronized (JersyRestClient.class)
            {
                if (instance == null)
                {
                    instance = new JersyRestClient();
                }
            }
        }
        return instance;
    }

    public T getContent(final String resourceUrl)
    {
        //get content
        //return T
    }

}

Upvotes: 0

Views: 122

Answers (2)

Paul Janssens
Paul Janssens

Reputation: 722

I'd say only if it's contravariant or abstract.

Upvotes: 0

lexicore
lexicore

Reputation: 43671

JersyRestClient<T> does not make much sense. You will return something specific in getInstance(). What will it be?

  • Either the raw type (JersyRestClient). In this case you can spare the <T>.
  • Some specific type JersyRestClient<MyContent>. Possible but does not make much sense.
  • You could do <T> JersyRestClient<T> getInstance() which will result in a cast to JersyRestClient<T>.

The type parameter T allows parameterizing instances of JersyRestClient. If you only have one instance, there's nothing to parameterize.

Upvotes: 2

Related Questions