学习Java的最大难点在于不知道谁调用谁,不像在C中,逻辑关系明确。
下面的list()调用accept()就是一个例子。
改编自Java编程思想526页
//新曙光培训@西安
//www.xinshuguang.org
import java.io.*;
import java.util.*;
public class xsgDirList{
public static void main(String[] args){
File path=new File(".");
path.list(new xsgDirFilter());
}
}
class xsgDirFilter implements FilenameFilter{
public boolean accept(File dir,String name){
System.out.println("不知道谁调用谁?");
return true;
}
}
另外,中文版的这一段翻译的也太差劲了吧:
DirFilter’s sole reason for existence is to provide the accept( ) method to the list( ) method so that list( ) can "call back" accept( ) to determine which file names should be included in the list. Thus, this structure is often referred to as a callback. More specifically, this is an example of the Strategy design pattern, because list( ) implements basic functionality, and you provide the Strategy in the form of a FilenameFilter in order to complete the algorithm necessary for list( ) to provide its service. Because list( ) takes a FilenameFilter object as its argument, it means that you can pass an object of any class that implements FilenameFilter to choose (even at run time) how the list( ) method will behave. The purpose of a Strategy is to provide flexibility in the behavior of code.
DirFilter这个类存在的唯一原因就是将accept()方法。
!!!!!中文版526页