[設計模式] javascript 之 迭代子模式

迭代子模式:定義this

迭代子模式,又稱遊標模式,是一種用於對彙集進行順序訪問規則的模式,是一種行爲模式;它用於提供對彙集對象的一種統一的訪問接口,使客戶可以在不瞭解彙集對象內部結構的狀況對彙集對象進行訪問。它涉及兩個部分,一個是彙集對象,一個迭代子對象,迭代對象(Iterator)用於提供訪問彙集對象的標題訪問方法;spa

主要組成角色:prototype

  • 抽象迭代子角色:用於定義訪問彙集的標準方法
  • 具體迭代子角色:用於實現訪問彙集的訪問方法
  • 抽象彙集角色:用於定義公共的彙集對象訪問方法,主要的有迭代對象,當前元素獲取,彙集對象大小;
  • 具體彙集角色:用於實現彙集對象的公共訪問;

基礎代碼:code

//抽象彙集對象類
public Collections() {
     this.arrs = ['xx'];
     this.iterator = function() {
          console.log('須要返回一個Iterator對象');
          return null;
     };

     this.size = function() { //Iterator 須要引用
         this.arrs.length;
     }

     this.get = function(idx) { //Iterator 須要引用
         return this.arrs[idx];
    }
};

//迭代對象
public Iterator (colls) {
     this.colls = colls;
     this.index = 0;
     this.next = function() {
         if > this.colls.size() //引用
         this.index ++ ;
     }

     this.prev = function() {
        //if < 0
        this.index--;
    }

    this.get = function() {
        this.colls.get(this.index); //引用
    }

    //more
}

迭代子模式結構圖 對象

實例blog

1. 抽象迭代角色接口

function abstractIterator() {
     this.prev = functiojn() {
     };

     this.next = function() {
       
     };

     this.first = function() {

     };

     this.hasNext = function() {

    };

    this.get = function() {

    };
}

2. 具體迭代角色get

function Iterator(colls) {
     this.colls = colls;
     this.index = 0;
};

Inteator.prototype = abstractIterator.prototype;

Inteator.prototype.prev = function() {
    if (this.index > 0)
        this.index --;
};

Inteator.prototype.next = function() {
   if (this.index < this.colls.size()) {
        this.index++;
  }
};

Inteator.prototype.first = function() {
   this.index = 0;
};

Inteator.prototype.hasNext = function() {
   return this.index < this.colls.size();
};

Inteator.prototype.get = function() {
   return this.colls.get(this.index);
};

3. 抽象彙集角色it

function abstractCollection() {
      this.iterator = function() {
           return null;
      };
}

4. 具體實現彙集角色公共方法io

function Collection() {
     this.arrars = ['XXX', 'yyy', 'ZZZ'];
};

Collection.prototype = abstractCollection.prototype;

Collection.prototype.iterator = function() {
     return new Iterator(this);
};

Collection.prototype.size = function() {
    return this.arrays.length;
};

Collection.prototype.get = function(index) {
     return this.arrays[index];
};

5. 客戶端使用

function Client() {
    var colls = new Collection();
    var iterator = colls.iterator();

    for (iterator.hasNext()) {
         console.log(iterator.get());
         iterator.next();
    }
};

其餘說明

把聚象對象的訪問邏輯統一到迭代對象裏,讓客戶能夠不用瞭解聚象對象的結構,就能夠一種統一的方式訪問,彙集與業務邏輯的解耦!

相關文章
相關標籤/搜索