java 组合模式
谁可以帮我解释一下这个组合模式啊 还有就是组合模式的具体应用场合啊
希望用比较形象的说法 小弟真的不懂啊
谢谢啦
package edu.scit.composite;
import java.util.*;
public interface IFile {
public void printName();
public boolean addChild(IFile file);
public boolean removeChild(IFile file);
public List<IFile> getChildren();
}
//树形结构的叶子结点
class File implements IFile{
private String name;
public File(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
public boolean addChild(IFile file) {
return false;
}
public boolean removeChild(IFile file) {
return false;
}
public List<IFile> getChildren() {
return null;
}
}
//树形结构的枝节点
class Folder implements IFile {
private String name;
private List <IFile> childList;
public Folder(String name) {
this.name = name;
this.childList = new ArrayList<IFile>();
}
public void printName() {
System.out.println(name);
}
public boolean addChild(IFile file) {
return childList.add(file);
}
public boolean removeChild(IFile file) {
return childList.remove(file);
}
public List<IFile> getChildren() {
return childList;
}
}
class Client {
public static void main(String[] args) {
//构造一个树形的文件/目录结构
Folder rootFolder = new Folder("c:\\");
Folder compositeFolder = new Folder("composite");
rootFolder.addChild(compositeFolder);
Folder windowsFolder = new Folder("windows");
rootFolder.addChild(windowsFolder);
File file = new File("TestComposite.java");
compositeFolder.addChild(file);
//从rootFolder访问整个对象群
printTree(rootFolder);
}
private static void printTree(IFile ifile) {
ifile.printName();
List <IFile> children = ifile.getChildren();
for (IFile file:children) {
if (file instanceof File) {
System.out.print(" ");
file.printName();
} else if (file instanceof Folder) {
printTree(file);
}
}
}
}