組合模式就是用小的子對象來構建更大的對象,而這些小的子對象自己也許是由更 小的「孫對象」構成的。javascript
//文件夾類
function Folder(name) {
this.name = name;
this.files = [];
this.parent = null;
}
Folder.prototype.add = function(file) {
file.parent = this;
this.files.push(file);
}
Folder.prototype.scan = function() {
console.log('開始掃描文件夾 => ',this.name);
for (let i=0; i<this.files.length; i++) {
const file = this.files[i];
file.scan();
}
}
Folder.prototype.remove = function(file) {
if (!this.parent) {
return false;
}
const files = this.files;
const len = files.length;
for (let i=files[len]; i >= 0; i--) {
if (files[i] === file) {
files.splice(i,1);
}
}
}
// 文件類
function File(name) {
this.name = name;
this.parent = null;
}
File.prototype.add = function() {
throw new Error('file下面不能添加文件');
}
File.prototype.scan = function() {
console.log('開始掃描文件 => ',this.name);
}
File.prototype.remove = function() {
if (!this.parent) {
return false;
}
const files = this.files;
const len = files.length;
for (let i=files[len-1]; i >= 0; i--) {
if (files[i] === file) {
files.splice(i,1);
}
}
}
const Ftimo = new Folder('Ftimo');
const Ffe = new Folder('Ffe');
const Fjs = new Folder('Fjs');
const Fes6 = new Folder('Fes6');
const Freact = new Folder('Freact');
const Fredux = new Folder('Fredux');
const findex = new File('findex');
const fcss = new File('fcss');
const fless = new File('fless');
const fjavascript = new File('fjavascript');
const fjava = new File('fjava');
Ftimo.add(Ffe);
Ffe.add(Fjs);
Ffe.add(Fes6);
Fjs.add(findex);
Fjs.add(fcss);
Fjs.add(fless);
Ffe.add(fjavascript);
Ffe.add(fjava);
Fjs.add(Freact);
Fjs.add(Fredux);
Ftimo.scan();
複製代碼
複製代碼