# Iterator ### 定義:不需要知道聚合物間的內部細節,即可依序存取內含的每個元素 #### 例如創造一個List去搭配一個ListIterator(外部Iterator)  #### 內部Iterator  ```ruby= class AlphabeticalOrderIterator include Enumerable attr_accessor :reverse private :reverse attr_accessor :collection private :collection def initialize(collection, reverse = false) @collection = collection @reverse = reverse end def each(&block) return @collection.reverse.each(&block) if reverse @collection.each(&block) end end class WordsCollection attr_accessor :collection private :collection def initialize(collection = []) @collection = collection end def iterator AlphabeticalOrderIterator.new(@collection) end def reverse_iterator AlphabeticalOrderIterator.new(@collection, true) end def add_item(item) @collection << item end end collection = WordsCollection.new collection.add_item('First') collection.add_item('Second') collection.add_item('Third') puts 'Straight traversal:' collection.iterator.each { |item| puts item } puts "\n" puts 'Reverse traversal:' collection.reverse_iterator.each { |item| puts item } ``` ##### 由上述例子中其實可以看到,Collection(or List)與Iterator其實是有關連的,客戶端傳入的巡訪對象必須依照特定的聚合結構,而若是要依據不同聚合結構來改變Iterator的話,就要使用**多型巡訪**(polymorphic iteration)  ### 使用時機 1. 即使隊聚合物件內部結構一無所知,依然可以存取物件內容 2. 想以多種方式巡訪聚合物件時 3. 想用一至介面巡訪各種不同聚合結構時(多型巡訪)  ### 設計優點 1. 可以提供多種巡訪方式 2. Iterator簡化Aggregate介面 3. 針對同一聚合體,可以同時存在許多巡訪者駐足其中
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up