如何使用构造函数来构建责任链来初始化链。这是我的 Runner.class,我正在使用setNext 方法构建我的链。
public class Runner {
private static final String ENTER_PATH = "Enter path: ";
private static final String FILTER_BY_NAME = "Filter by name? (0/1)";
private static final String ENTER_NAME_PARAMETER = "Enter name parameter please: ";
private static final String FILTER_BY_EXTENSION = "Filter by extension? (0/1)";
private static final String ENTER_EXTENSION_PARAMETER = "Enter extension please (without '.'): ";
private static final String FILTER_BY_SIZE = "Filter by size? (0/1)";
private static final String ENTER_SIZE_TO = "Enter upper limit searching files in kb";
private static final String ENTER_SIZE_FROM = "Enter lower limit searching files in kb";
private static final String TRUE="1";
private Scanner scanner;
private List<File> fileList;
public Runner() {
this.scanner = new Scanner(System.in);
this.fileList = new ArrayList<>();
}
private String getDirName(){
System.out.println(ENTER_PATH);
return scanner.nextLine();
}
private Handler getChainOfResponsibility(){
GeneralHandler generalHandler = new GeneralHandler();
Handler lastHandler = generalHandler;
System.out.println(FILTER_BY_NAME);
if (scanner.nextLine().equals(TRUE)) {
System.out.println(ENTER_NAME_PARAMETER);
String name = scanner.nextLine();
Handler nameHandler = new NameHandler(name);
lastHandler.setHandler(nameHandler);
lastHandler = nameHandler;
}
System.out.println(FILTER_BY_EXTENSION);
if (scanner.nextLine().equals(TRUE)) {
System.out.println(ENTER_EXTENSION_PARAMETER);
Handler extensionHandler = new ExtensionHandler(scanner.nextLine());
lastHandler.setHandler(extensionHandler);
lastHandler = extensionHandler;
}
System.out.println(FILTER_BY_SIZE);
if (scanner.nextLine().equals(TRUE)) {
System.out.println(ENTER_SIZE_FROM);
double fromSize = scanner.nextDouble();
System.out.println(ENTER_SIZE_TO);
double toSize = scanner.nextDouble();
Handler sizeHandler = new SizeHandler(fromSize, toSize);
lastHandler.setHandler(sizeHandler);
}
return generalHandler;
}
public void run() throws InterruptedException, IOException {
findAllFiles(getDirName(), getChainOfResponsibility());
showListOfFilteredFiles();
}
这是我的处理程序抽象类
public abstract class Handler {
private Handler handler;
public void setHandler(Handler handler) {
this.handler = handler;
}
protected abstract boolean handleFilter(File file);
public boolean doFilter(File file){
if(handleFilter(file)){
if(Objects.nonNull(handler)){
return handler.doFilter(file);
}
return true;
}
return false;
}
}
而且我也有它的实施。如何制作,它将通过构造函数初始化!请帮忙!