組合模式,將對象組合成樹形結構以表示“部分-整體”的層次結構,組合模式使得用戶對單個對象和組合對象的使用具有一致性,組合模式可以讓客戶端像修改配置文件一樣簡單的完成本來需要流程控制語句來完成的功能。
特點:對於遞歸或者類似樹形的分級數據結構,可以用最簡單的方式進行處理。
企業級開發和常用框架中的應用:系統目錄結構和網站導航結構
下面以目錄結構舉例:
場景:假設我們現在有一個目錄,目錄下面還有子目錄和文件,現在我們要查看整個目錄及目錄下的所有文件和創建時間
具體代碼如下:
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(); } }}組合模式更像是一種遍歷手段,但是這種手段也有一些限制,比如只能針對類似於樹形結構的數據。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。