1. 程式人生 > 實用技巧 >Centos7上一次War包的部署與執行

Centos7上一次War包的部署與執行

迭代器模式

迭代器模式Iterator Pattern提供了一種方法順序訪問一個聚合物件中的各個元素,而又無需暴露該物件的內部實現,這樣既可以做到不暴露集合的內部結構,又可讓外部程式碼透明地訪問集合內部的資料,迭代器模式屬於行為型模式。

描述

迭代器模式是針對集合物件而生的,對於集合物件而言,肯定會涉及到對集合的新增和刪除操作,同時也肯定支援遍歷集合元素的操作,我們此時可以把遍歷操作放在集合物件中,但這樣的話,集合物件既承擔太多的責任了,面向物件設計原則中有一條就是單一職責原則,所有我們要儘可能地分離這些職責,用不同的類取承擔不同的責任,迭代器模式就是用迭代器類來承擔遍歷集合的職責。

優點

  • 支援以不同的方式遍歷一個聚合物件,並可以簡化聚合類。
  • 在同一個聚合上可以有多個遍歷。
  • 在迭代器模式中,增加新的聚合類和迭代器類都很方便,無須修改原有程式碼。
  • 迭代器模式使得訪問一個聚合物件的內容而無需暴露它的內部表示,即迭代抽象。
  • 迭代器模式為遍歷不同的集合結構提供了一個統一的介面,從而支援同樣的演算法在不同的集合結構上進行操作。

缺點

  • 迭代器模式將儲存資料和遍歷資料的職責分離,增加新的聚合類需要對應增加新的迭代器類,類的個數成對增加,這在一定程度上增加了系統的複雜性。
  • 迭代器模式在遍歷的同時更改迭代器所在的集合結構可能會導致出現異常,不能在遍歷的同時更改集合中的元素數量。

適用環境

  • 訪問一個聚合物件的內容而無須暴露它的內部表示。
  • 需要為聚合物件提供多種遍歷方式。
  • 為遍歷不同的聚合結構提供一個統一的介面。

實現

// 廣播電臺示例

class RadioStation { // 電臺
    constructor(frequency) {
        this.frequency = frequency;
    }
    
    getFrequency() {
        return this.frequency;
    }
}

class StationList { // 迭代器
    constructor(){
        this.index = -1;
        this.stations = [];
    }

    get(i){
        return this.stations[this.index];
    }

    hasNext(){
        let index = this.index + 1;
        return this.stations[index] !== void 0;
    }

    next(){
        return this.stations[++this.index];
    }

    addStation(station) {
        this.stations.push(station);
    }
    
    removeStation(toRemove) {
        const toRemoveFrequency = toRemove.getFrequency();
        this.stations = this.stations.filter(station => station.getFrequency() !== toRemoveFrequency);
    }
}

(function(){
    const stationList = new StationList();
    stationList.addStation(new RadioStation(89));
    stationList.addStation(new RadioStation(101));
    stationList.addStation(new RadioStation(102));
    stationList.addStation(new RadioStation(103.2));
    stationList.stations.forEach(station => console.log(station.getFrequency())); // 89 101 102 103.2
    stationList.removeStation(new RadioStation(89));
    while(stationList.hasNext()) console.log(stationList.next().getFrequency()); // 101 102 103.2
})();

每日一題

https://github.com/WindrunnerMax/EveryDay

參考

https://www.cnblogs.com/xuwendong/p/9898030.html
https://www.runoob.com/design-pattern/iterator-pattern.html
https://github.com/sohamkamani/javascript-design-patterns-for-humans#-iterator