0

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
    }

}
Karan Khanna
  • 1,947
  • 3
  • 21
  • 49
  • why wouldn't that be possible? – Stultuske Mar 19 '18 at 10:59
  • 1
    *I thing the rest client should be implemented as a Singleton class.* - Singleton is [often considered an anti-pattern](https://stackoverflow.com/questions/12755539/why-is-singleton-considered-an-anti-pattern). – lexicore Mar 19 '18 at 10:59
  • I fully agree with lexicore that choosing to go with a Singleton is a decision you shouldn't do just like that as the implications can be more than just annoying in later stages of development. Should you however decide to go with a Singleton please use an `enum` for it. This is simply the most efficient way to make a Singleton in Java, way simpler to use and way less error prone then using anything else to implement the pattern. – Ben Mar 19 '18 at 11:05
  • Have a look here for further information on that topic: https://stackoverflow.com/questions/26285520/implementing-singleton-with-an-enum-in-java – Ben Mar 19 '18 at 11:06

2 Answers2

2

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.

lexicore
  • 42,748
  • 17
  • 132
  • 221
0

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

Paul Janssens
  • 622
  • 3
  • 9