策略模式(回调函数)
/** * */ package com.zachary.io.util; import java.io.File; import java.io.IOException; /** * @author Zachary.Zheng * @version 1.0 * @date 2019年11月9日 */ public class ProcessFiles { /** * 定义回调函数接口 * 在调用时实现 * @author Zachary.Zheng * @version 1.0 * @date 2019年11月9日 */ public interface Strategy{ void process(File file); } private Strategy strategy; private String ext; public ProcessFiles(Strategy strategy, String ext) { super(); this.strategy = strategy; this.ext = ext; } public ProcessFiles() { super(); } public void start(String [] args) { try { if(args.length == 0) { processDirectoryTree(new File(".")); } else { for (String arg : args) { File fileArg = new File(arg); if(fileArg.isDirectory()) { processDirectoryTree(fileArg); } else { if(!arg.endsWith("." + ext)) { arg += "." + ext; } // 执行回调函数 strategy.process(new File(arg).getCanonicalFile()); } } } } catch (Exception e) { // TODO: handle exception } } public void processDirectoryTree(File root) throws IOException { for(File file: Directory.walk(root.getAbsolutePath(), ".*\\."+ext)) { // 执行回调函数 strategy.process(file.getCanonicalFile()); } } public static void main(String[] args) { new ProcessFiles(new ProcessFiles.Strategy() { // 回调函数 public void process(File file) { System.out.println(file); } }, "java").start(args);; } } /* Output: (sample) E:\\javaBaseLearn\\IOStream\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\Directory.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\DirList.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\DirList2.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\DirList3.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\PPrint.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\ProcessFiles.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\TreeInfo.java *///:~