firemail

标题: 组合模式实现树形结构支持查询返回查找遍历删除等 [打印本页]

作者: Qter    时间: 2021-8-4 14:38
标题: 组合模式实现树形结构支持查询返回查找遍历删除等
本帖最后由 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. }
复制代码







欢迎光临 firemail (http://firemail.wang:8088/) Powered by Discuz! X3