Discuz! Board

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 960|回复: 0
打印 上一主题 下一主题

组合模式实现树形结构支持查询返回查找遍历删除等

[复制链接]

1228

主题

1996

帖子

7570

积分

认证用户组

Rank: 5Rank: 5

积分
7570
跳转到指定楼层
楼主
发表于 2021-8-4 14:38:43 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 Qter 于 2021-8-4 15:10 编辑

https://blog.csdn.net/LoveLion/article/details/7956898

https://blog.csdn.net/liyf2/article/details/109019508  
组合模式:如何设计实现支持递归遍历的文件系统目录树结构?
  1. public class FileSystemNode {
  2.   private String path;
  3.   private boolean isFile;
  4.   private List<FileSystemNode> subNodes = new ArrayList<>();

  5.   public FileSystemNode(String path, boolean isFile) {
  6.     this.path = path;
  7.     this.isFile = isFile;
  8.   }

  9.   public int countNumOfFiles() {
  10.     // TODO:...
  11.   }

  12.   public long countSizeOfFiles() {
  13.     // TODO:...
  14.   }

  15.   public String getPath() {
  16.     return path;
  17.   }

  18.   public void addSubNode(FileSystemNode fileOrDir) {
  19.     subNodes.add(fileOrDir);
  20.   }

  21.   public void removeSubNode(FileSystemNode fileOrDir) {
  22.     int size = subNodes.size();
  23.     int i = 0;
  24.     for (; i < size; ++i) {
  25.       if (subNodes.get(i).getPath().equalsIgnoreCase(fileOrDir.getPath())) {
  26.         break;
  27.       }
  28.     }
  29.     if (i < size) {
  30.       subNodes.remove(i);
  31.     }
  32.   }

复制代码


https://www.jianshu.com/p/853748b177bf
  1. const Folder = function (name) {
  2.   this.name = name
  3.   this.parent = null
  4.   this.files = []
  5. }

  6. Folder.prototype.add = function (file) {
  7.   file.parent = this
  8.   this.files.push(file)
  9. }

  10. Folder.prototype.scan = function () {
  11.   console.log('开始扫描文件夹: ' + this.name)
  12.   for (let i = 0, file, files = this.files; file = files[i++];) {
  13.     file.scan()
  14.   }
  15. }

  16. Folder.prototype.remove = function () {
  17.   if (!this.parent) {
  18.     return
  19.   }
  20.   for (let files = this.parent.files, len = files.length - 1; len >= 0; len--) {
  21.     let file = files[len]
  22.     if (file === this) {
  23.       files.splice(len, 1)
  24.     }
  25.   }
  26. }

  27. const File = function (name) {
  28.   this.name = name
  29.   this.parent = null
  30. }

  31. File.prototype.add = function () {
  32.   throw new Error('文件下面不能再添加文件')
  33. }

  34. File.prototype.remove = function () {
  35.   if (!this.parent) {
  36.     return
  37.   }
  38.   for (let files = this.parent.files, len = files.length - 1; len >= 0; len--) {
  39.     let file = files[len]
  40.     if (file === this) {
  41.       files.splice(len, 1)
  42.     }
  43.   }
  44. }

  45. File.prototype.scan = function () {
  46.   console.log('开始扫描文件: ' + this.name)
  47. }
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|firemail ( 粤ICP备15085507号-1 )

GMT+8, 2024-4-19 18:21 , Processed in 0.054531 second(s), 19 queries .

Powered by Discuz! X3

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表