1. 程式人生 > >23種設計模式之(二十三)迭代器模式(python_c++實現) .md

23種設計模式之(二十三)迭代器模式(python_c++實現) .md

23種設計模式之(二十三)迭代器模式(Iterator)

本文主要介紹23種設計模式之迭代器模式,附詳細python/c++示例程式碼。

  • 概念
  • 應用場景
  • 注意事項
  • 程式碼示例
  • 總結
  • 程式碼連結

迭代器模式(Iterator)

概念

迭代模式,是行為模式之一,它把對容器中包含的內部物件的訪問委讓給外部類,使用Iterator(遍歷)按順序進行遍歷訪問的設計模式。

迭代器模式就是為了有效地處理按順序進行遍歷訪問的一種設計模式,簡單地說,Iterator模式提供一種有效的方法,可以遮蔽聚集物件集合的容器類的實現細節,而能對容器內包含的物件元素按順序進行有效的遍歷訪問。

GoF對迭代器模式的定義是:提供一種方法順序訪問一個聚合物件中各個元素, 而又不需暴露該物件的內部表示。

應用場景

(1)、訪問一個聚合物件的內容而無須暴露它的內部表示。

(2)、需要為聚合物件提供多種遍歷方式。

(3)、為遍歷不同的聚合結構提供一個統一的介面。

C++程式碼示例

/************************************************************************/
/* 設計模式專題
/*
/* 迭代器模式
/*
/* Author  : zzl
/*
/* 程式設計環境: window10 vs2010
/*
/* Date    : 20180918
/************************************************************************/
#include <iostream> typedef int Object ; #define SIZE 5 class MyIterator { public: virtual void First() = 0; virtual void Next() = 0; virtual bool IsDone() = 0; virtual Object CurrentItem() = 0; }; class Aggregate { public: virtual MyIterator *CreateIterator() = 0; virtual Object getItem
(int index) = 0; virtual int getSize() = 0; }; class ContreteIterator : public MyIterator { public: ContreteIterator(Aggregate *ag) { _ag = ag; _current_index = 0; } virtual void First() { _current_index = 0; //讓當前 遊標 回到位置0 } virtual void Next() { if (_current_index < _ag->getSize()) { _current_index ++; } } virtual bool IsDone() { return (_current_index == _ag->getSize()); } virtual Object CurrentItem() { return _ag->getItem(_current_index); } protected: private: int _current_index; Aggregate *_ag; }; class ConcreteAggregate : public Aggregate { public: ConcreteAggregate() { for (int i=0; i<SIZE; i++) { object[i] = i + 100; } } virtual MyIterator *CreateIterator() { return new ContreteIterator(this); //讓迭代器 持有一個 集合的 引用 } virtual Object getItem(int index) { return object[index]; } virtual int getSize() { return SIZE; } private: Object object[SIZE]; }; void main() { Aggregate * ag = new ConcreteAggregate; MyIterator *it = ag->CreateIterator(); for (; !(it->IsDone()); it->Next() ) { printf ("%d ",it->CurrentItem()); } delete it; delete ag; }

python程式碼示例

# -*- coding: utf-8 -*-
###################################################################
# 設計模式專題
# 
# 迭代器模式
# 
# Author  : zzl
# 
# 程式設計環境: window10 python2.7
# 
# Date    : 20180918
##################################################################
# python語言本身對可迭代物件有良好的支援,只要物件定義了可以返回一個迭代器的__iter__方法,
# 或者定義了可以支援下標索引的__getitem__方法(這些雙下劃線方法會在其他章節中全面解釋),那麼它就是一個可迭代物件。


class Aggregate(object):
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]


if __name__ == "__main__":
    from collections import Iterable

    agg = Aggregate([100, 200, 300, 400])
    for obj in agg:
        print(obj)

原始碼連結