网友您好, 请在下方输入框内输入要搜索的题目:
【Java代码】
import Java.util.ArrayList;
import java.util.List;
(1) class AbstractFile{
protected String name;
public void printName(){System.out.println(name);}
public abstract boolean addChild(AbstractFile file);
public abstract boolean removeChild(AbstractF ile file);
public abstract List<AbstractFile> getChildren();
}
class File extends AbstractFile{
public File(String name){this.name=name;}
public boolean addChild(AbstractFile file){return false;}
public boolean removeChild(AbstractFile file){return false;}
public List<AbstractFile> getChildren(){return (2) ;}
}
class Folder extends AbstractFile{
private List <AbslractFile> childList;
public Folder(String name){
this.name=name;
this.childList=new ArrayList<AbstractFile>();
}
public boolean addChild(AbstractFile file) { return childList.add(file);}
public boolean removeChild(AbstractFile file){return childList.remove(file);}
public (3) <AbstractFile> getChildren(){return (4) ;}
}
public class Client{
public static void main(String[] args){
//构造一个树形的文件/目录结构
AbstractFile rootFolder= new Folder("c:\\ ");
AbstractFile compositeFolder=new Folder("composite");
AbstractFile windowsFolder=new Folder("windows");
AbstractFile file=new File("TestComposite.java");
rootFolder.addChild(compositeFolder) ;
rootFolder.addChild(windowsFolder);
compositeFolder.addChild(file) ;
//打印目录文件树
printTree(rootFolder);
}
private static void printTree(AbslractFile ifile){
ifile.printName();
List <AbslractFile> children=ifile.getChildreno:
if(children==null) return;
for (AbstractFile file:children) {
(5) ;
}
}
}
该程序运行后输出结果为:
c:\
composite
TestComposite.java
Windows
参考答案