合成模式把部分和整體的關係用樹結構表示出來。使客戶端把一個個單獨的成分對象和由它們複合而成的合成對象同等看待。
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();
}
}