|
本帖最后由 Qter 于 2021-8-4 15:10 编辑
https://blog.csdn.net/LoveLion/article/details/7956898
https://blog.csdn.net/liyf2/article/details/109019508
组合模式:如何设计实现支持递归遍历的文件系统目录树结构?
- public class FileSystemNode {
- private String path;
- private boolean isFile;
- private List<FileSystemNode> subNodes = new ArrayList<>();
- public FileSystemNode(String path, boolean isFile) {
- this.path = path;
- this.isFile = isFile;
- }
- public int countNumOfFiles() {
- // TODO:...
- }
- public long countSizeOfFiles() {
- // TODO:...
- }
- public String getPath() {
- return path;
- }
- public void addSubNode(FileSystemNode fileOrDir) {
- subNodes.add(fileOrDir);
- }
- public void removeSubNode(FileSystemNode fileOrDir) {
- int size = subNodes.size();
- int i = 0;
- for (; i < size; ++i) {
- if (subNodes.get(i).getPath().equalsIgnoreCase(fileOrDir.getPath())) {
- break;
- }
- }
- if (i < size) {
- subNodes.remove(i);
- }
- }
复制代码
https://www.jianshu.com/p/853748b177bf
- const Folder = function (name) {
- this.name = name
- this.parent = null
- this.files = []
- }
- Folder.prototype.add = function (file) {
- file.parent = this
- this.files.push(file)
- }
- Folder.prototype.scan = function () {
- console.log('开始扫描文件夹: ' + this.name)
- for (let i = 0, file, files = this.files; file = files[i++];) {
- file.scan()
- }
- }
- Folder.prototype.remove = function () {
- if (!this.parent) {
- return
- }
- for (let files = this.parent.files, len = files.length - 1; len >= 0; len--) {
- let file = files[len]
- if (file === this) {
- files.splice(len, 1)
- }
- }
- }
- const File = function (name) {
- this.name = name
- this.parent = null
- }
- File.prototype.add = function () {
- throw new Error('文件下面不能再添加文件')
- }
- File.prototype.remove = function () {
- if (!this.parent) {
- return
- }
- for (let files = this.parent.files, len = files.length - 1; len >= 0; len--) {
- let file = files[len]
- if (file === this) {
- files.splice(len, 1)
- }
- }
- }
- File.prototype.scan = function () {
- console.log('开始扫描文件: ' + this.name)
- }
复制代码
|
|