1. 迭代器模式
定义:迭代器模式(iterator Pattern)提供一个对象来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示
分类:行为型模式
2. 任务
- 现在有一个电脑文件夹(AForlder),包含 BForlder+BText+BMp3,BForlder 包含 CText
- 增加函数实现文件夹的遍历
- 再理解
不暴露聚合对象的内部表示
3. JS 实现
3.1. 方式一:
class Forlder {
constructor(name) {
this._name = name;
this._childred = new Array();
}
addChild(item) {
this._childred.push(item);
}
getChildren() {
return this._childred;
}
showAll() {
if (this.getChildren) {
console.log(this);
}
for (let i = 0; i < this._childred.length; i++) {
if (this._childred[i].getChildren && this._childred[i].getChildren().length > 0) {
this._childred[i].showAll();
} else {
console.log(this._childred[i]);
}
}
}
}
class TextFile {
constructor(name) {
this._name = name;
}
showTextName() {
return this._name;
}
}
class Mp3File {
constructor(name) {
this._name = name;
}
showMp3Name() {
return this._name;
}
}
//构造对象
let AForlder = new Forlder('AForlder');
let BForlder = new Forlder('BForlder');
let CText = new TextFile('CText');
BForlder.addChild(CText);
AForlder.addChild(BForlder);
let BText = new TextFile('BText');
AForlder.addChild(BText);
let BMp3 = new Mp3File('BMp3');
AForlder.addChild(BMp3);
//console.log(AForlder);
AForlder.showAll();
3.2. 方式二:
class Forlder {
constructor(name) {
this._name = name;
this._childred = new Array();
}
addChild(item) {
this._childred.push(item);
}
getChildren() {
return this._childred;
}
iterator() {
return this._childred[Symbol.iterator]();
}
}
class TextFile {
constructor(name) {
this._name = name;
}
showTextName() {
return this._name;
}
}
class Mp3File {
constructor(name) {
this._name = name;
}
showMp3Name() {
return this._name;
}
}
//构造对象
let AForlder = new Forlder('AForlder');
let BForlder = new Forlder('BForlder');
let CText = new TextFile('CText');
BForlder.addChild(CText);
AForlder.addChild(BForlder);
let BText = new TextFile('BText');
AForlder.addChild(BText);
let BMp3 = new Mp3File('BMp3');
AForlder.addChild(BMp3);
//console.log(AForlder);
let showObjects = function (objectInput) {
let it = objectInput.iterator();
for (let obj of it) {
if (obj.getChildren && obj.getChildren().length > 0) {
console.log(obj);
showObjects(obj);
} else {
console.log(obj);
}
}
};
showObjects(AForlder);