組合模式,將對象組合成樹形結構以表示“部分-整體”的階層,組合模式使得使用者對單個對象和組合對象的使用具有一致性,組合模式可以讓用戶端像修改設定檔一樣簡單的完成本來需要流程式控制制語句來完成的功能。
特點:對於遞迴或者類似樹形的分級資料結構,可以用最簡單的方式進行處理。
企業級開發和常用架構中的應用:系統目錄結構和網站導航結構
下面以目錄結構舉例:
情境:假設我們現在有一個目錄,目錄下面還有子目錄和檔案,現在我們要查看整個目錄及目錄下的所有檔案和建立時間
具體代碼如下:
package com.test.composite;import java.util.ArrayList;import java.util.Date;import java.util.List;public class Demo { public static void main(String[] args) { Date d = new Date(); Dir f1 = new Dir("我的收藏", d); d.setYear(2012); Dir f2 = new Dir("圖片", d); Dir f3 = new Dir("音樂", d); d.setYear(2013); ActualFile f4 = new ActualFile("喜洋洋與灰太狼.avi", d); f1.add(f4); ActualFile f5 = new ActualFile("taiyanghua.jpg", d); ActualFile f6 = new ActualFile("變形精鋼.jpg", d); f2.add(f5); f2.add(f6); f1.add(f2); f1.add(f3); f1.showFile(); }}/** * 首先目錄和檔案都屬於檔案,所以我們可以抽象一個抽象檔案出來 */interface AbstractFile { /** * 展示檔案方法 */ public void showFile();}/** * 真實檔案 */class ActualFile implements AbstractFile { private String name; private Date createDate; public ActualFile(String name, Date createDate) { this.name = name; this.createDate = createDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * 實現抽象檔案類的展示檔案方法 */ public void showFile() { System.out.println("檔案名稱:"+this.name+"--建立時間:"+this.createDate.getTime()); }}/** * 目錄檔案 */class Dir implements AbstractFile { private String name; private Date createDate; /** * 作為目錄檔案,會多出一個子檔案清單 */ private List<AbstractFile> list = new ArrayList<>(); public Dir(String name, Date createDate) { super(); this.name = name; this.createDate = createDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * 目錄檔案的添加操作,為目錄添加子檔案或者子目錄 */ public void add(AbstractFile f){ this.list.add(f); } /** * 目錄檔案的刪除操作,刪除子檔案或者子目錄 */ public void remove(AbstractFile f){ this.list.remove(f); } /** * 目錄檔案的擷取操作,擷取目錄下面的子檔案或者子目錄 */ public AbstractFile getIndex(int index){ return this.list.get(index); } public void showFile() { System.out.println("目錄名:"+this.name+"--建立時間:"+this.createDate.getTime()); for(AbstractFile f:list){ f.showFile(); } }}
組合模式更像是一種遍曆手段,但是這種手段也有一些限制,比如只能針對類似於樹形結構的資料。
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。