组合模式的关键在于,将对象合成树形结构,用来表示‘部分-整体’的层次结构。 通过对象的多态性表现,使用户对单个对象和组合对象的使用有一致性。
客户将统一使用组合结构中所有的对象,而不需要关心它究竟是组合对象还是单个对象。
例:
- 当我们要开始一个一个扫描文件夹的时候,文件和文件夹在一个树形结构下。使用组合模式可以让用户不用关心其之间的区别。
var Folder = function (name) {
this.name = name;
this.files = [];
this.parents = null;
}
Folder.prototype.add = function (file) {
file.parents = this
this.files.push(file);
}
Folder.prototype.scan = function () {
console.log('开始扫描' + this.name)
for (let i = 0; i < this.files.length; i++) {
this.files[i].scan()
}
}
var File = function (name) {
this.name = name;
this.parents = null;
}
File.prototype.add = function (file) {
throw error('子文件夹不能添加');
}
File.prototype.scan = function () {
console.log('开始检索' + this.name);
}
File.prototype.remove = function () {
console.log('开始移除' + this.name);
if (!this.parents) {
return
}
for (let i = this.parents.files.length - 1; i >= 0; i--) {
var file = this.parents.files[i]
if (file == this) {
this.parents.files.splice(i, 1)
}
}
}
var Folder1 = new Folder('a文件夹')
var File1 = new File('js')
var File2 = new File('es6')
Folder1.add(File1)
Folder1.add(File2)
File1.remove()
Folder1.scan()
上述例子的一致性体现在 scan方法。remove方法。 用户不用管是当前对象是组合对象还是单个对象。
javaScript设计模式与开发实践