輕松控制java組合形式。本站提示廣大學習愛好者:(輕松控制java組合形式)文章只能為提供參考,不一定能成為您想要的結果。以下是輕松控制java組合形式正文
組合形式,將對象組分解樹形構造以表現“部門-全體”的條理構造,組合形式使得用戶對單個對象和組合對象的應用具有分歧性,組合形式可讓客戶端像修正設置裝備擺設文件一樣簡略的完本錢來須要流程掌握語句來完成的功效。
特色:關於遞歸或許相似樹形的分級數據構造,可以用最簡略的方法停止處置。
企業級開辟和經常使用框架中的運用:體系目次構造和網站導航構造
上面以目次構造舉例:
場景:假定我們如今有一個目次,目次上面還有子目次和文件,如今我們要檢查全部目次及目次下的一切文件和創立時光
詳細代碼以下:
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();
}
}
}
組合形式更像是一種遍歷手腕,然則這類手腕也有一些限制,好比只能針對相似於樹形構造的數據。
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。