How can I "register" a class which implements an interface to create objects based on the "registered" class? Let me explain what I want to do:
I an coding a request processor for my thread pooled server and I want the request processor can be "configured" on the server so I can choose which request processor the server should use for it's requests. Here is how I think it should have worked:
// yes I know the interface can't extend the abstract Thread class ...
// see in the Server class what I want to do with it
public interface RequestProcessor extends Thread {
public final Socker socket;
RequestProcessor(final Socket paramSocket) {
socket = paramSocket;
}
// abstract so each request processor implementing this interface
// has to handle the request in his specific way
abstract void run();
}
public class RequestProcessorA implements RequestProcessor {
RequestProcessorA(final Socket paramSocket) {
super(paramSocket);
}
@Override
public void run() {
// do something with the request
}
}
public class RequestProcessorB implements RequestProcessor {
RequestProcessorB(final Socket paramSocket) {
super(paramSocket);
}
@Override
public void run() {
// do something different with the request
}
}
So having this as interface (or as abstract class to be able to extend the Thread class) I want to create a server and tell him to use wheater RequestProcessorA or RequestProcessorB like:
public class Server extends Thread {
private final RequestProcessor processor;
private final ServerSocker server;
Server(final int paramPort, final RequestProcessor paramProcessor) {
processor = paramProcessor;
server = new ServerSocket(paramPort);
}
@Override
public void run() {
while (true) {
Socket socket = server.accept();
// how can I create a new RequestProcessorA object if "processor" is type of RequestProcessorA???
// how can I create a new RequestProcessorB object if "processor" is type of RequestProcessorB???
// how can I create a new CustomProcessor object if "processor" is type of CustomProcessor???
RequestProcessor rp = ???;
// add rp to the thread pool
}
}
}
So how to design such requirements? I wan't to make this an extendable library so others can simply use the server and just have to code their own request processors by extendimg/implementing my interface/abstract class and simply "register" their own request processor?
I hope you guys understand what I mean. And sorry if this is a dup but I dont really know the technical terms for this :/
java.util.ServiceLoader.