import java.util.List;
import java.util.ArrayList;
import java.io.*;
//抽象类
abstract class AbstractFile {
protected String Name;
public void printName(){
System.out.println(Name);
}
public abstract boolean addChild(AbstractFile file);
public abstract boolean removeChild(AbstractFile file);
public abstract List<AbstractFile> getChildren();
}
//文件夹类
class Folder extends AbstractFile {
private List<AbstractFile> childList;
File f1 ;
public Folder(String name){
Name = name;
f1 = new File(Name);
if(f1.mkdir()){
System.out.println("目录创建成功了。");
}
this.childList = new ArrayList<AbstractFile>();
}
public boolean addChild(AbstractFile file){
return childList.add(file);
}
public boolean removeChild(AbstractFile file){
return childList.remove(file);
}
public List<AbstractFile> getChildren(){
return childList;
}
}
//文件类
class File2 extends AbstractFile {
File f2 ;
public File2(String name){
Name = name;
f2 = new File(Name);
if(f2.mkdir()){
System.out.println("目录创建成功了222。");
}
}
public boolean addChild(AbstractFile file){
return false ;
}
public boolean removeChild(AbstractFile file){
return false ;
}
public List<AbstractFile> getChildren(){
return null;
}
}
//测试类
public class Client {
//主方法
public static void main(String[] args) {
AbstractFile rootFolder = new Folder("C:/Test");
AbstractFile compositeFolder = new Folder("composite");
AbstractFile compositeFolder2 = new Folder("composite2");//
AbstractFile windowFolder = new Folder("windows");
AbstractFile file = new File2("TestComposite.java");
rootFolder.addChild(compositeFolder);
rootFolder.addChild(windowFolder);
compositeFolder.addChild(compositeFolder2);//
compositeFolder.addChild(file);
PrintTree(rootFolder);
}
//构建文件目录树方法
public static void PrintTree(AbstractFile ifile){
ifile.printName();
List<AbstractFile> children = ifile.getChildren();
if(children == null){
return ;
}
for(AbstractFile file2:children){
//file2.printName();
//递归调用,实现对文件子目录的打印
PrintTree(file2);
}
}
}
|
|