在这种情况下,您通常会向Matcher提供某种工厂,该工厂负责创建适当的线程。在Java8中,您可以使用
Supplier
接口:
public class Matcher {
private final Supplier<? extends MatcherThread> threadSupplier;
public Matcher(Supplier<? extends MatcherThread> threadSupplier) {
this.threadSupplier = threadSupplier;
}
protected List<Integer> runAll(List<String> clusters, int nthreads) {
MatcherThread task = threadSupplier.get();
task.setSubcluster(subcluster);
tasks.add(task);
}
}
Matcher matcher = new Matcher(() -> new MaxLength());
这假设您添加了
setSubcluster
方法,而不是构造函数注入。或者,您也可以使用
Function