杜嘉豪
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    DP7 組合模式、迭代器模式 === ###### tags: `DesignPatterns` 參考 [Design Patterns Elements of Reusable Object-Oriented Software](http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf) [大話設計模式](https://www.tenlong.com.tw/products/9789866761799) [UML工具](https://plantuml-editor.kkeisuke.com/#) [DesignPatternsPHP](https://github.com/domnikl/DesignPatternsPHP/blob/master/Behavioral/State/OrderContext.php) [Head First Design Patterns: A Brain-friendly Guide](https://www.books.com.tw/products/F010315469) [汤姆大叔的博客: 深入理解JavaScript系列](https://www.cnblogs.com/TomXu/archive/2011/12/15/2288411.html) [從實例學設計模式 by Jace Ju](http://slides.com/jaceju/design-patterns-by-examples/#/) # 組合模式(Composite pattern) ## 大話: ### 定義: 組合模式,將物件組合成樹形結構以表示 "部分 - 整體" 的層次結構。組合模式使得用戶對單個物件和組合物件的使用具有一致性。 #### 使用時機: 當需求中是表現部分與整體層次的結構時,以及你希望用戶可以忽略組合物件與單個物件的不同,統一地使用組合結構中的所有物件時,就應該考慮用組合模式了。 (p.283) p.277 讓整體與部分可以被一致對待 ### 討論: - 哪邊有用到呢? - MVC 模式、文件系統、企業結構。 - 哪邊可以用? - 假如今天有個功能是能夠申請成為"電商開店優良輔導店家",能夠讓店家自行經營管理底下的開店平台,這時候對 WACA 來說不論是輔導店家的店,或是店家底下的店家在系統上都是一樣的,差別可能在於需要去一層層紀錄這間店的源頭店家是誰。(有點多層次直銷概念 a.k.a 老鼠會...) [從應用角度來看,如果你想把一對多的關係,轉換為一對一的關係(一致性的行為), 那麼你可以看到組合模式所帶來的好處。](https://dotblogs.com.tw/ricochen/2012/08/08/73906) ## GOF ![](https://i.imgur.com/udY4tjH.png) ![](https://i.imgur.com/mYatgRm.png) ![](https://i.imgur.com/QC37H6C.png) ![](https://i.imgur.com/lK3pWkH.png) ![](https://i.imgur.com/d2HBG3r.png) ![](https://i.imgur.com/TKos2zE.png) ![](https://i.imgur.com/jRonMdp.png) #### 實作組合模式的時候有幾點要考慮: 1. Explicit parent references. 2. Sharing components. 3. Maximizing the Component interface. 4. Declaring the child management operations. 5. Should Component implement a list of Components? 6. Child ordering. 7. Caching to improve performance. 8. Who should delete components? 9. What's the best data structure for storing components? --- 1. **明確定義父節點參考。** 維護子元件與父節點間的參考,讓遍歷組合模式的結構更加方便,並且簡化了元件的新增刪除。父節點參考,也對使用 責任鏈模式 (Chain-of-responsibility pattern) 有所幫助。 通常定義父節點參考在 Conponent 中。如此一來 Leaf 和 Composite 類別可以方便地繼承或是管理。 要透過父節點參考去遍歷所有子 Composite,必須確保父節點的變動只會發生在從一個 Composite 中新增或移除的時候。 2.共享 Components。 共享 Components 經常有許多好處。例如可以透過共享 Components 來達到節省儲存空間。但當 Component 在沒有 patent 或是有多個 parent 的情況下,共享元件的難度會大大提高。 要在有多個 Parent 下共享元件,可以透過將所有 parents 儲存在 Componet 中,但這樣會使得原本的樹多出不必要的結構。 享元模式(Flyweight Pattern) 中實現了在避免儲存所有父節點的情況下使用共享元件並能夠在需要取得部分或全部元件狀態時不必透過他們的父節點。 ??????????????? 3. **最大化元件的介面** 組合模式的其中一個目的就是讓所有的 Leaf 或是 Composite 都能被客戶端視為一致的對待。 為了達到這個目的,在設計 Component 類別時應該盡可能地將所有 Composite 和 Leaf 會用到的方法列出來,並由 Composite 和 Leaf 去決定如何實作。 但這樣的規劃與設計類別結構的原則有所牴觸,在設計一個類別的時候應該指定一對他的子類別有意義的方法。而對 Leaf 來說,顯然有許多方法是用不到的。 4. 承 3,雖然牴觸類別設計的原則,但在 組合模式 中,我們的重點是 **"能被一致的對待"**,所以透明度(Leaf, Composite, Component 的一致)應該要比安全性(Leaf 中存在不必要的方法)來的重要。 5. 一個 Component 是否應該實作所有的 Components? 這樣雖然很方便,但是對於 Leaf 來說也相當於浪費了很多冗餘的空間,更遑論對於末端的節點來說沒有任何功用。只有在當Children 數量很少時再考慮這麼做。 6. Child 的排序。就像前面舉得畫圖例子一樣。在畫布中每個元件都有他的圖層順序,才能夠由後往前呈現。當我們需要類似的功能時,可以考慮使用 Ilerator Pattern 來達成。 7. 改進效能,再以畫畫工具為例,工具箱中的所有工具都經常被使用,那麼經常遍歷或搜尋 Compositions 的成本就變高。這時候可以考慮將這些 Composite Cache 住,並且宣告一個介面去控制由當前 Component 是誰去禁用其他 Component 以及他們連帶的 Parent,確保只有當下切換的 Component 可以作用。 8. 移除 Components。在沒有GC機制的語言中,最好的移除方式就是在Composite Destoryed 時移除其 Children。但當某個 Leaf 是 immutable 或是 shareable 的狀態下例外。 9. Composite Pattern 最適合用什麼結構來儲存? linked list, trees, arrays, hash tables? 挑選的準則只有一個,依照不同情境去設計 Composite 並依照 Composite 結構去選擇最有效率的方式。 #### Related Patterns - Often the component-parent link is used for a Chain of Responsibility (251). - Decorator (196) is often used with Composite. When decorators and composites are used together, they will usually have a common parent class. So decorators will have to support the Component interface with operations like Add, Remove, and GetChild. - Flyweight (218) lets you share components, but they can no longer refer to their parents. - Iterator (289) can be used to traverse composites. - Visitor (366) localizes operations and behavior that would otherwise be distributed across Composite and Leaf classes. 現代框架的 MVC 模式,多借鏡於 Smarttalk,而 Smarttalk 中的 MVC 模式就是一種 Composite pattern。 ----- # 迭代器模式(Iterator pattern) ## 大話: ### 定義: 迭代器模式,提供一種方法依序存取一個聚合物件中各個元素,而又不暴露該物件的內部表示。 #### 使用時機: 當你需要存取一個聚集物件,而且不管這些物件是什麼都需要走遍的時候,你就應該考慮用迭代器模式。(p.295) 需要對聚集有 **多種方式** 走遍時,可以考慮用迭代器模式。(p.259) 未走遍不同的聚集結構提供如 **開始、下一個、是否結束、現在在哪裡** 等統一的介面。(p.259) **迭代器模式就是分離了集合物件的走遍行為,抽象出一個迭代器類別來負責,這樣既可以做到不暴露集合的內部結構,又可以讓外部程式碼透明地存取集合內部的資料。** 在存取陣列、集合、列表等資料時,尤其是資料庫操作,非常普遍。但也因為太普遍了,大部分高階語言皆有提供封裝,故反而覺得此模式不常用。(p.302) [你知道for、foreach和Iterator遍历有什么(效率)区别吗](https://www.jianshu.com/p/bbb220824c9a) --- ## GOF ### Intent - **Provide a way to access the elements of an aggregate objectsequentially without exposing its underlying representation.** ![](https://i.imgur.com/vQcOeaM.png) ![](https://i.imgur.com/oThnMru.png) --- ![](https://i.imgur.com/xX5Wtwn.png) ![](https://i.imgur.com/9q6256C.png) ![](https://i.imgur.com/qCPkuJZ.png) ### Implementation (p.292) 1. Who controls the iteration? 可以由外部控制,較為彈性。但也可以交由迭代器自己控制自己比較方便。 3. Who defines the traversal algorithm? 4. How robust is the iterator? 5. Additional Iterator operations. 可以自己在迭代器中定義額外的方法,例如 SKIP 等等。 7. Using polymorphic iterators in C++. 8. Iterators may have privileged access. 9. Iterators for composites. 10. Null iterators. ### Related Patterns - Composite (183):Iterators are often applied to recursive structures such as Composites. - Factory Method (121):Polymorphic iterators rely on factory methods to instantiate the appropriate Iterator subclass. - Memento (316) is often used in conjunction with the Iterator pattern. An iteratorcan use a memento to capture the state of an iteration. The iteratorstores the memento internally. 可以配合組合模式去遍歷個個元件組合。 可以依照工廠方法去實例化對應的迭代器。 可以配合備忘錄模式(Memento)達到回復上一動、上上一動的效果。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    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

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully