Interfaces - 注册class继承接口以创建基于class的对象

Interfaces - register class inheriting interface to create objects based on the class

我如何"register"一个class实现一个接口来创建基于"registered"class的对象?让我解释一下我想做什么:

我正在为我的线程池服务器编写请求处理器,我希望请求处理器可以 "configured" 在服务器上,这样我就可以选择服务器应为其请求使用哪个请求处理器。这是我认为它应该起作用的方式:

// 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
}

}

因此将其作为接口(或作为抽象 class 以便能够扩展线程 class)我想创建一个服务器并告诉他使用 wheater RequestProcessorA 或 RequestProcessorB,例如:

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
    }
}

}

那么如何设计这样的需求呢?我不想把它变成一个可扩展的库,这样其他人就可以简单地使用服务器,只需要通过 extendimg/implementing 我的 interface/abstract class 和 "register" 来编写他们自己的请求处理器他们自己的请求处理器?

希望你们明白我的意思。对不起,如果这是一个骗子,但我真的不知道这个的技术术语:/

您将要使用 Abstract Factory pattern。创建一个工厂接口,并为您可能想要生产的每个 class 创建一个实现:

public interface IRequestProcessorFactory {
    RequestProcessor create(Socket paramSocket);
}

并像这样实现它:

public class RequestProcessorAFactory implements IRequestProcessorFactory {
    public RequestProcessor create(Socket paramSocket) {
        return new RequestProcessorA(paramSocket);
    }
}

并将其实例传递给 Server。然后,调用

RequestProcessor rp = factory.create(socket);

获取 RequestProcessorARequestProcessorB 的内容,具体取决于通过的工厂。