java23种设计模式(五)--组合模式
转载:https://www.cnblogs.com/V1haoge/p/6489827.html
定义:所谓组合模式,其实说的是对象包含对象的问题,通过组合的方式(在对象内部引用对象)来进行布局,我认为这种组合是区别于继承的,而另一层含义是指树形结构子节点的抽象(将叶子节点与树枝节点抽象为子节点),区别于普通的分别定义叶子节点与数枝节点的方式。
使用场景:这种组合模式正是应树形结构而生,所以组合模式的使用场景就是出现树形结构的地方。比如:文件目录显示,多及目录呈现等树形结构数据的操作。
1、创建抽象类:Node
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * author:YZH 3 * time: 2019/6/12 15:36 4 * description: 抽象类Node 5 **/ 6 public abstract class Node { 7 8 protected String name; 9 10 public Node(String name){ 11 this.name = name; 12 } 13 //新增节点:文件节点无此方法,目录节点重写此方法 14 public void addNode(Node node) throws Exception{ 15 throw new Exception("Invalid exception"); 16 } 17 //显示节点:文件与目录均实现此方法 18 abstract void display(); 19 }
2、创建叶子节点(继承Node)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * author:YZH 3 * time: 2019/6/12 15:39 4 * description: 文件实现类(叶子节点) 5 **/ 6 public class Filer extends Node { 7 8 public Filer(String name) { 9 super(name); 10 } 11 12 @Override 13 void display() { 14 System.out.println(name); 15 } 16 }
3、创建非叶子节点(继承Node)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * author:YZH 3 * time: 2019/6/12 15:40 4 * description: 目录实现类(非叶子节点) 5 **/ 6 public class Noder extends Node{ 7 private List<Node>nodeList = new ArrayList<>(); 8 9 public Noder(String name) { 10 super(name); 11 } 12 13 @Override 14 public void addNode(Node node) throws Exception { 15 nodeList.add(node); 16 } 17 18 /** 19 * 递归循环显示 20 */ 21 @Override 22 void display() { 23 System.out.println(name); 24 for (Node node : nodeList) { 25 node.display(); 26 } 27 } 28 }
4、测试代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * author:YZH 3 * time: 2019/6/12 15:43 4 * description: 测试代码 5 **/ 6 public class Client { 7 public static void createNode(Node node) throws Exception { 8 File file = new File(node.name); 9 File[] f = file.listFiles(); 10 for(File fi : f){ 11 if(fi.isFile()){ 12 Filer filer = new Filer(fi.getAbsolutePath()); 13 node.addNode(filer); 14 } 15 if(fi.isDirectory()){ 16 Noder noder = new Noder(fi.getAbsolutePath()); 17 node.addNode(noder); 18 createNode(noder);//使用递归生成树结构 19 } 20 } 21 } 22 23 public static void main(String[] args) { 24 Node noder = new Noder("C:\\Users\\11655\\Desktop\\gbase"); 25 try { 26 createNode(noder); 27 } catch (Exception e) { 28 e.printStackTrace(); 29 } 30 noder.display(); 31 } 32 }
运行结果:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 C:\Users\11655\Desktop\gbase 2 C:\Users\11655\Desktop\gbase\2019-06-09 11时.xls 3 C:\Users\11655\Desktop\gbase\drivers 4 C:\Users\11655\Desktop\gbase\drivers\gbase8a 5 C:\Users\11655\Desktop\gbase\drivers\gbase8a\gbase-connector-java-8.3.81.53-build-54.5.1-bin.jar 6 C:\Users\11655\Desktop\gbase\drivers\gbase8a\log.properties 7 C:\Users\11655\Desktop\gbase\drivers\gbase8s 8 C:\Users\11655\Desktop\gbase\drivers\gbase8s\ifxjdbc.jar 9 C:\Users\11655\Desktop\gbase\drivers\gbase8t