組合模式,將對(duì)象組合成樹形結(jié)構(gòu)以表示“部分-整體”的層次結(jié)構(gòu),組合模式使得用戶對(duì)單個(gè)對(duì)象和組合對(duì)象的使用具有一致性,組合模式可以讓客戶端像修改配置文件一樣簡(jiǎn)單的完成本來需要流程控制語句來完成的功能。
特點(diǎn):對(duì)于遞歸或者類似樹形的分級(jí)數(shù)據(jù)結(jié)構(gòu),可以用最簡(jiǎn)單的方式進(jìn)行處理。
企業(yè)級(jí)開發(fā)和常用框架中的應(yīng)用:系統(tǒng)目錄結(jié)構(gòu)和網(wǎng)站導(dǎo)航結(jié)構(gòu)
下面以目錄結(jié)構(gòu)舉例:
場(chǎng)景:假設(shè)我們現(xiàn)在有一個(gè)目錄,目錄下面還有子目錄和文件,現(xiàn)在我們要查看整個(gè)目錄及目錄下的所有文件和創(chuàng)建時(shí)間
具體代碼如下:
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();  }}/** * 首先目錄和文件都屬于文件,所以我們可以抽象一個(gè)抽象文件出來 */interface AbstractFile { /** * 展示文件方法 */ public void showFile();}/** * 真實(shí)文件 */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; } /** * 實(shí)現(xiàn)抽象文件類的展示文件方法 */ public void showFile() { System.out.println("文件名:"+this.name+"--創(chuàng)建時(shí)間:"+this.createDate.getTime()); }}/** * 目錄文件 */class Dir implements AbstractFile { private String name; private Date createDate; /** * 作為目錄文件,會(huì)多出一個(gè)子文件列表 */ 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+"--創(chuàng)建時(shí)間:"+this.createDate.getTime()); for(AbstractFile f:list){  f.showFile(); } }}組合模式更像是一種遍歷手段,但是這種手段也有一些限制,比如只能針對(duì)類似于樹形結(jié)構(gòu)的數(shù)據(jù)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選