合成模式把部分和整体的关系用树结构表示出来。使客户端把一个个单独的成分对象和由它们复合而成的合成对象同等看待。
public interface IFile {
//返回自己的实例
IFile getComposite();
//某个商业方法
void sampleOperation();
//获取深度
int getDeep();
//设置深度
void setDeep(int x);
}
public class File implements IFile {
private String name; // 文件名字
private int deep; // 层级深度
public File(String name) {
this.name = name;
}
// 返回自己的实例
public IFile getComposite() {
return this;
}
// 某个商业方法
public void sampleOperation() {
System.out.println("sampleOperation");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDeep() {
return deep;
}
public void setDeep(int deep) {
this.deep = deep;
}
}
public class Folder implements IFile{
private String name = null; //文件名字
private int deep; //层级深度,根深度为0
private Vector<IFile> componentVector = new Vector<IFile>();
public Folder(String name) {
this.name = name;
}
//返回自己的实例
public IFile getComposite() {
return this;
}
public void sampleOperation() {
System.out.println("sampleOperation");
}
//增加一个文件或文件夹
public void add(IFile iFile) {
componentVector.add(iFile);
iFile.setDeep(this.deep + 1);
}
//删除一个文件或文件夹
public void remove(IFile iFile) {
componentVector.removeElement(iFile);
}
//返回直接子文件(夹)集合
@SuppressWarnings("unchecked")
public Vector getAllComponent() {
return componentVector;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDeep() {
return deep;
}
public void setDeep(int deep) {
this.deep = deep;
}
}
public class Client {
public static String indentChar = "\t"; // 文件层次缩进字符
public static void main(String args[]) {
new Client().test();
}
/**
* 客户端测试方法
*/
public void test() {
// 根下文件及文件夹
Folder root = new Folder("树根");
Folder b1_1 = new Folder("1_枝1");
Folder b1_2 = new Folder("1_枝2");
Folder b1_3 = new Folder("1_枝3");
File l1_1 = new File("1_叶1");
File l1_2 = new File("1_叶2");
File l1_3 = new File("1_叶3");
// b1_2下的文件及文件夹
Folder b2_1 = new Folder("2_枝1");
Folder b2_2 = new Folder("2_枝2");
File l2_1 = new File("2_叶1");
// 缔造树的层次关系(简单测试,没有重复添加的控制)
root.add(b1_1);
root.add(b1_2);
root.add(l1_1);
root.add(l1_2);
b1_2.add(b2_1);
b1_2.add(b2_2);
b1_2.add(l2_1);
root.add(l1_3);
root.add(b1_3);
// 控制台打印树的层次
outTree(root);
}
public void outTree(Folder folder) {
System.out.println(folder.getName());
iterateTree(folder);
}
/**
* 遍历文件夹,输入文件树
*
* @param folder
*/
@SuppressWarnings("unchecked")
public void iterateTree(Folder folder) {
Vector<IFile> clist = folder.getAllComponent();
for (IFile file : clist) {
if (file instanceof Folder) {
Folder cm = (Folder) file;
System.out.println(getIndents(file.getDeep()) + cm.getName());
iterateTree(cm);
} else {
System.out.println(getIndents(file.getDeep()) + ((File) file).getName());
}
}
}
/**
* 文件层次缩进字符串
*
* @param x
* 缩进字符个数
* @return 缩进字符串
*/
public static String getIndents(int x) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < x; i++) {
sb.append(indentChar);
}
return sb.toString();
}
}