合成(Composite)模式是一種非常重要的設計模式
一
從原理圖可見
當然
二
這裡主要用到樹的遞歸遍歷
廢話就不說了
/**
* Created by IntelliJ IDEA
* User: leizhimin
* Date:
* 抽象文件角色
*/
public interface IFile {
//返回自己的實例
IFile getComposite();
//某個商業方法
void sampleOperation();
//獲取深度
int getDeep();
//設置深度
void setDeep(int x);
}
import java
/**
* Created by IntelliJ IDEA
* User: leizhimin
* Date:
* 文件夾角色
*/
public class Folder implements IFile {
private String name; //文件名字
private int deep; //層級深度
private Vector<IFile> componentVector = new Vector<IFile>();
public Folder(String name) {
this
}
//返回自己的實例
public IFile getComposite() {
return this;
}
//某個商業方法
public void sampleOperation() {
System
}
//增加一個文件或文件夾
public void add(IFile IFile) {
componentVector
IFile
}
//刪除一個文件或文件夾
public void remove(IFile IFile) {
componentVector
}
//返回直接子文件(夾)集合
public Vector getAllComponent() {
return componentVector;
}
public String getName() {
return name;
}
public void setName(String name) {
this
}
public int getDeep() {
return deep;
}
public void setDeep(int deep) {
this
}
}
/**
* Created by IntelliJ IDEA
* User: leizhimin
* Date:
* 文件
*/
public class File implements IFile {
private String name; //文件名字
private int deep; //層級深度
public File(String name) {
this
}
//返回自己的實例
public IFile getComposite() {
return this;
}
//某個商業方法
public void sampleOperation() {
System
}
public String getName() {
return name;
}
public void setName(String name) {
this
}
public int getDeep() {
return deep;
}
public void setDeep(int deep) {
this
}
}
import java
import java
/**
* Created by IntelliJ IDEA
* User: leizhimin
* Date:
* 遍歷樹的一個測試
*/
public class Client {
public static String indentChar =
public static void main(String args[]) {
new Client()
}
/**
* 客戶端測試方法
*/
public void test() {
//根下文件及文件夾
Folder root = new Folder(
Folder b
Folder b
Folder b
File l
File l
File l
//b
Folder b
Folder b
File l
//締造樹的層次關系(簡單測試
root
root
root
root
b
b
b
root
root
//控制台打印樹的層次
outTree(root);
}
public void outTree(Folder folder) {
System
iterateTree(folder);
}
/**
* 遍歷文件夾
*
* @param folder
*/
public void iterateTree(Folder folder) {
Vector<IFile> clist = folder
//todo:遍歷之前可以對clist進行排序
for (Iterator<IFile> it = erator(); it
IFile em = it
if (em instanceof Folder) {
Folder cm = (Folder) em;
System
iterateTree(cm);
} else {
System
}
}
}
/**
* 文件層次縮進字符串
*
* @param x 縮進字符個數
* @return 縮進字符串
*/
public static String getIndents(int x) {
StringBuilder sb = new StringBuilder();
for (int i =
sb
}
return sb
}
}
三
控制台輸出如下
可見
四
原文出處
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27351.html