组合模式
概述
代码示例
/*
* 文件节点抽象(是文件和目录的父类)
*/
public interface IFile {
//显示文件或者文件夹的名称
public void display();
//添加
public boolean add(IFile file);
//移除
public boolean remove(IFile file);
//获得子节点
public List<IFile> getChild();
}
public class File implements IFile {
private String name;
public File(String name) {
this.name = name;
}
public void display() {
System.out.println(name);
}
public List<IFile> getChild() {
return null;
}
public boolean add(IFile file) {
return false;
}
public boolean remove(IFile file) {
return false;
}
}
public class Folder implements IFile{
private String name;
private List<IFile> children;
public Folder(String name) {
this.name = name;
children = new ArrayList<IFile>();
}
public void display() {
System.out.println(name);
}
public List<IFile> getChild() {
return children;
}
public boolean add(IFile file) {
return children.add(file);
}
public boolean remove(IFile file) {
return children.remove(file);
}
}
主函数
public class MainClass {
public static void main(String[] args) {
//C盘
Folder rootFolder = new Folder("C:");
//beifeng目录
Folder beifengFolder = new Folder("beifeng");
//beifeng.txt文件
File beifengFile = new File("beifeng.txt");
rootFolder.add(beifengFolder);
rootFolder.add(beifengFile);
//ibeifeng目录
Folder ibeifengFolder = new Folder("ibeifeng");
File ibeifengFile = new File("ibeifeng.txt");
beifengFolder.add(ibeifengFolder);
beifengFolder.add(ibeifengFile);
Folder iibeifengFolder = new Folder("iibeifeng");
File iibeifengFile = new File("iibeifeng.txt");
ibeifengFolder.add(iibeifengFolder);
ibeifengFolder.add(iibeifengFile);
displayTree(rootFolder,0);
}
public static void displayTree(IFile rootFolder, int deep) {
for(int i = 0; i < deep; i++) {
System.out.print("--");
}
//显示自身的名称
rootFolder.display();
//获得子树
List<IFile> children = rootFolder.getChild();
//遍历子树
for(IFile file : children) {
if(file instanceof File) {
for(int i = 0; i <= deep; i++) {
System.out.print("--");
}
file.display();
} else {
displayTree(file,deep + 1);
}
}
}
}