前端杂记让前端飞

组合模式实现文件夹操作

2018-12-24  本文已影响2人  会飞小超人

组合模式如果运用得当,可以大大简化客户的代码。一般来说,组合模式适用于以下这两种情况。

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)
}

let folder = new Folder('学习资料')
let folder1 = new Folder('JavaScript')
let folder2 = new Folder('jQuery')

let file1 = new File('JavaScript设计模式与开始实践')
let file2 = new File('精通jQuery')
let file3 = new File('重构与模式')

folder1.add(file1)
folder2.add(file2)

folder.add(folder1)
folder.add(folder2)
folder.add(file3)

folder.scan()

folder1.remove()

folder.scan()

但是,组合模式并不是完美的,他可能会产生一个这样的系统:系统中每个对象看起来都与其他对象差不多。它们的区别只有在运行的时候才会显现出来,这会使代码难以理解。此外,如果通过组合模式创建了太多的对象,那么这些对象可能会让系统担负不起。

上一篇 下一篇

猜你喜欢

热点阅读