I have following design requirements:
interface Server {}public class ServerImpl implements Server {}, must be a Singletonpublic class ServerABC extends ServerImpl {}public class ServerXYZ extends ServerImpl {}
Now I want to put methods in class Server their implementation should be given by either ServerABC or ServerXYZ.
In ServerImpl
public class ServerImpl implements Server {
private static Server server;
public static synchronized RESTClient getInstance() {
if (server == null) {
server = new ServerImpl ();
}
return server;
}
}
How can I make this work?
If I put methods in Server interface, ServerImpl has to implement it but I want the subclasses (ServerABC and ServerXYZ) to provide implementation. These methods should be called using ServerImpl object.
I consider that the best way is to avoid the Singleton pattern. If you only need one instance, then create just one instance. Singleton is been known to make testing more difficult and doesn’t really bring a huge benefit.
What I would do in your situation is:
ServerImplan abstract class. All the methods that should be implemented in a subclass must be marked abstract as well. There are cases where you want that only one of the subclasses to provide an implementation for a specific method. In this case, just throw anUnsupportedOperationExceptionin the classes that must not implement it. ORServerImpland simply have the 2 other classes implement the interface. If the classServerImpldoesn’t implement much on its own, then this is the better way to go.