package com.design; import java.io.File; import java.util.ArrayList; import java.util.List; /**组合模式 * 应树形结构而生,所以组合模式的使用场景就是出现树形结构的地方。比如:文件目录显示,多及目录呈现等树形结构数据的操作 * Created by nicknailo on 2018/8/20. */ public class CombinatorialPattern { public static void main(String[] args) { Noder noder = new Noder("./../"); createTree(noder); noder.display(); } public static void createTree(Noder noder){ File file = new File(noder.nodeName); File[] f = file.listFiles(); for(File f1 : f){ if( f1.isFile() ){ Filer filer = new Filer(f1.getAbsolutePath()); noder.addFiler(filer); } if(f1.isDirectory()){ Noder noder1 = new Noder(f1.getAbsolutePath()); noder.addNoder(noder1); // 使用递归生成树结构 createTree(noder1); } } } } class Noder{ String nodeName; List<Noder> noderList = new ArrayList<Noder>(); List<Filer> filerList = new ArrayList<Filer>(); public Noder(String nodeName) { this.nodeName = nodeName; } public void addNoder(Noder noder){ noderList.add(noder); } public void addFiler(Filer filer){ filerList.add(filer); } public void display(){ for(Noder noder: noderList){ System.out.println( noder.nodeName ); // 递归显示子目录 noder.display(); } for (Filer filer : filerList){ System.out.println( filer.filename ); } } } class Filer{ String filename; public Filer(String filename) { this.filename = filename; } public void display(){ System.out.println( filename ); } }
参考:https://www.cnblogs.com/V1haoge/p/6489827.html