JS设计模式-04-迭代器模式

1. 迭代器模式

定义:迭代器模式(iterator Pattern)提供一个对象来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示
分类:行为型模式

2. 任务

  1. 现在有一个电脑文件夹(AForlder),包含 BForlder+BText+BMp3,BForlder 包含 CText
  2. 增加函数实现文件夹的遍历
  3. 再理解不暴露聚合对象的内部表示

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值