轻松掌握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();
 }
 }

}

组合模式更像是一种遍历手段,但是这种手段也有一些限制,比如只能针对类似于树形结构的数据。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。