B3) Composite(組合模式)
定義:將對象組合成樹(shù)狀結構來(lái)形成“部分-整體”層次。組合使得客戶(hù)端同樣地處理單個(gè)對象和組合對象。
組合模式在dofactory中使用頻率為最高的LV5,實(shí)在是面向對象的一個(gè)經(jīng)典的模式,而且樹(shù)狀結構是現實(shí)中除了二維表格外最常用的數據結構。舉最簡(jiǎn)單的例子,有一大堆檔案,通常的保管方法就是按照拼音字母分類(lèi),放在不同的檔案夾中,再將所有的檔案夾放入抽屜,當然,可能有些檔案無(wú)非分類(lèi),就不放在檔案夾中而是直接放入抽屜。如果有新的檔案A,就放入A檔案夾中,要找檔案S,就從檔案夾S中拿,而要轉移所有檔案,就轉移整個(gè)抽屜。這樣就將檔案組合成檔案夾,檔案夾與檔案再組合成抽屜,形成樹(shù)狀結構。電腦中存放文件(file)的方式也是如此,現在只考慮對文件的刪除。文件對象如下表示:
public interface FileEntry {
public void remove();
}
public File implements FileEntry {
private String name;
public File(String name) {
this.name = name;
}
public void remove() {
System.out.println("File " + name + " has been deleted.");
}
}
文件目錄(文件夾)對象
public Dir implements FileEntry {
private List files;
private String name;
public Dir(String name) {
this.name = name;
this.files = new ArrayList();
}
public void add(FileEntry fileEntry) {
files.add(fileEntry);
}
public void remove() {
Iterator itr = files.iterator();
While (itr.hasNext()) {
FileEntry fileEntry = (FileEntry)itr.next();
fileEntry.remove();
}
System.out.println("Dir " + name + " has been deleted.");
}
}
對于文件夾的操作
Dir dirRoot = new Dir("root");
Dir dirSub = new Dir("sub");
File fileA = new File("A.file");
File fileB = new File("B.file");
File fileX = new File("X.file");
File file1 = new File("1.file");
dirSub.add(fileA);
dirSub.add(fileB);
dirSub.add(fileX);
dirRoot.add(dirSub);
dirRoot.add(file1);
//delete
dirRoot.remove();
這樣,所有的文件和文件夾都會(huì )被刪除,這里面還用到了以前提到的Iterator模式來(lái)進(jìn)行對象的遍歷。還有一部分功能沒(méi)有完成,現在只是對組合對象的處理,而對單個(gè)對象的處理并沒(méi)有實(shí)現,就是通過(guò)dirRoot對象刪除某個(gè)文件或者文件夾。由于這部分功能涉及后面要說(shuō)的一個(gè)模式Chain Of Responsibility(職責鏈),暫時(shí)不提以免混淆,而功能將會(huì )在以后講COR的時(shí)候補充完整。
參考:
1、 http://www.jdon.com/designpatterns/composite.htm(中文、java實(shí)例)
2、 http://www.dofactory.com/Patterns/PatternComposite.aspx(英文、C#實(shí)例、UML)
3、 http://www.techscore.com/tech/DesignPattern/Composite.html(日文、java實(shí)例、UML)推薦
聯(lián)系客服