杜嘉豪
    • 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
    DP6 狀態模式、備忘錄模式 === ###### 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) # 狀態模式 ### 定義: 當一個物件內在狀態改變時允許改變其行為,這個物件看起來像是改變了其類別。 Allow an object to alter its behavior when its internal state changes.The object will appear to change its class. 允許一個物件在其內部狀態改變的同時改變其行為,並且就像是改變了物件類別一樣。 --- #### 大話: 摘要: p.239 狀態模式主要解決的是當控制一個物件狀態轉換的條件運算是過於複雜時的情況。透過把狀態的判斷邏輯轉移到表示不同狀態的一系列類別當中,可以把複雜的判斷邏輯簡化。(但當狀態很簡單時,就沒必要使用了) p.241 將與特定狀態相關的行為局部化,並且將不同狀態的行為分割開來。 p.241 將特定的狀態相關的行為都放入一個物件中,由於所有與狀態相關的程式碼都存在於某個ConcreteState中,所以透過定義新的子類別,可以很容易地增加新的狀態和轉換。 p.241 消除了龐大的條件分支敘述,大部分的分支判斷會使得他們拿以修改和擴展,任何的改動和變化都是致命的。 狀態模式透過把各種狀態轉移邏輯分布到 State 的子類別之間,來減少相互間的依賴,變得容易維護與擴展。 使用時機: p.242 當一個物件的行為取決於它的狀態,而且必須在執行時刻根據狀態改變他的行為時,就可以考慮使用狀態模式。 --- #### HFDP: Q: 如果在程式之中 Context 具有許多實體,這些實體之間可以共用 State 物件嗎? A: 可以,但前提是 State 物件不能持有他們自己的內部狀態,否則就不能共用。(保證只有 Context 使用並使狀態物件改變,不會用到一半被 State 物件改變 State) 若想要共用狀態,你將每個狀態指定到靜態的實體變數中。如果你的狀態需要利用到 Context 中的方法或者實體變數,還是必須在每個 Hnadler() 方法內傳入 Context 參考。 Q: 該用抽象類別或是介面實踐 State 的狀態? A: 若沒有共同的功能可以放進抽象類別中,就會選擇使用介面。在實踐狀態模式時,很可能會想使用抽象類別,這樣一來,當你以後需要在抽象類別中加入新的方法,就很容易,不需要打破具象狀態的ㄈ封裝。 --- | 模式 | 敘述 | | -------- | -------- | | 狀態模式 | 將狀態的行為封裝起來,並將行為轉介到目前的狀態 ![](https://i.imgur.com/f3WDVxe.png) ![](https://i.imgur.com/vQJIkvx.png) | | 策略模式 | 將可以互換的行為封裝起來,然後使用轉介的方法,決定使用哪一個行為 ![](https://i.imgur.com/m0wwDoi.png) ![](https://i.imgur.com/hSUsyZO.png) | | 樣板模式 | 由次類別決定如何實踐演算法中的某些步驟 ![](https://i.imgur.com/ujCipnu.png) ![](https://i.imgur.com/NF3OR3f.png) | State ............................................................. 338 Strategy .......................................................... 349 Template Method ................................................... 360 --- 在一個最完整的TCP資料傳輸,會經過三個階段 第一階段利用『三向交握』(Three-Way Handshake)來達 成『建立連線』階段 第二階段的『資料傳輸』階段 最後則是在資料傳送完畢後的『關閉連線』(Close Connection)階段 - **允許一個物件在其內部狀態改變的同時改變其行為,並且就像是改變了物件類別一樣。** --- - 處理文件呈現的時候可能會有許多種斷行方式,**將他們(這些擁有共通行為但不同實踐的演算法家族)分別封裝起來,讓他們之間可以互相替換,讓演算法的變化,不會影響到使用演算法的客戶。**(例如特價、打折策略) --- 泡茶需要 加茶葉、加熱水 泡咖啡需要 加咖啡豆、加熱水、可能還需要加些牛奶 泡茶、泡咖啡,都需要加某種原料、也都需要加水、但泡茶不需要加牛奶 - **針對這種有共通的算法,透過範本方法可以定義一個操作中的演算法的骨架,而將依些步驟延遲到子類別中。範本方法使得子類別可以不改變一個演算法的"結構"即可重新定義該演算法的某些特定步驟。** --- 討論: 貨態改變??? 逆物流? --- #### GOF ### 適用的場合 - 當一個物件的行為取決於它的狀態,且按照執行期的狀態動態的改變其行為。 - 依照物件不同的狀態,透過複雜且龐大的條件判斷去決定物件的行為。通常這些條件判斷都有相似之處,狀態模式透過將每種判斷所產生的對應狀態獨立成一個獨立的狀態類別,可以簡單地在處理物件狀態的傳遞與行為的改變。 ![](https://i.imgur.com/EX9HlzF.png) ![](https://i.imgur.com/jQId1GX.png) ![](https://i.imgur.com/uHKcyzi.png) ![](https://i.imgur.com/vqD563A.png) ![](https://i.imgur.com/WM3XyUA.png) - Context 委派特定狀態請求到特定實體狀態物件中 - Context 可以透過將自身當作變數傳遞給狀態實體,使狀態實體能夠存取 Context - Context 為一直接面對 Client 的介面,Client 可以透過賦予 State 來設定 Context,且一旦設定過 State 後便能夠在無需直接接觸任何狀態物件下達成狀態的轉換。 - Context 或 ConcreteState 都有能力能夠決定狀態的改變。 GOF p.347 可以與Singleton(單例模式)一起運用,使每個狀態成為一個 獨體 --- # 備忘錄模式 #### 大話: ### 定義: 在不破壞封裝性的前提下,捕獲一個物件的內部狀態,並在該物件之外保存這個狀態。這樣以後就可以將該物件恢復到先前保存的狀態。 破壞封裝性,例如原本的書中的例子把腳色屬性細節等等全都暴露給用戶端,且用戶端還要負責設定,職責過大。 摘要: p.269 Memento 模式比較適用於功能比較複雜的,但需要維護或記錄屬性歷史的類別,或者需要保存的屬性只是眾多屬性中的一小部份時,Originator 可以根據保存的 Memento 資訊還原到前一狀態。 p.269 備忘錄可以把複雜的物件內部資訊對其他的物件遮罩起來。 管理者並不需要知道 State 的存在及保存細節。 討論: 商家設定復原,類似 GOOGLE DOC 能夠看到編輯紀錄(State),且能夠從記錄復原。 --- #### GOF: ### 備忘錄模式的主要成員 ![](https://i.imgur.com/jJnmnnY.png) ![](https://i.imgur.com/xcFhXUW.png) - Memeto (SolverState) - 儲存 Originator 物件的部分或全部的原始狀態 - 對 Originator 以外的物件拒絕存取。以 Caretaker 角度來說,Memeto 可視為一個單純只提供傳遞 Memeto 窄介面; 以Originator 角度來說,Memeto 提供了相對寬的介面好讓 Originator 存取保存在 Memeto 中的狀態屬性。 - Originator (ConstrainSolver) - 能夠建立 Memeto 並使其將當前狀態保存。 - 能夠利用 Memeto 還原內部狀態。 - Caretaker (undo mechanism) - 職責為安全的保全 Memeto - 永不直接操作或是檢查 Memeto 內容。 ### 時序圖 ![](https://i.imgur.com/zyg9e07.png) 備忘錄模式有幾個重點: 1. **保持封裝**。在 Originator 必須存取且在外部保存資料時,Memeto pattern 能夠避免對 Originator 之外暴露不必要的細節。 2. **簡化 Originator**。在保持封裝的前提下,若不使用 Memeto pattern,則我們必須將狀態保持等相關方法在 Originator 中實現,並必須在客戶端透過 Originator 調用這些方法還原或保存狀態。 3. **使用 Memeto pattern 可能耗費昂貴成本**。Memotos 在需要儲存的資訊太過龐大,或是客戶端頻繁的操作儲存或還原時,可能對系統造成負擔。除非保存與還原狀態的成本對系統來說可以很低廉,否則應該考慮使用 Memeto pattern 是否適當。 4. 限制存取介面大小(對 Originator 來說為寬,對 Caretaker 來說窄),但在某些語言上可能不好實作。 5. 看不見的保存狀態成本。對 Caretaker 來說,無法知道所要處理的 Memetos 大小,若 Memeto 非常大時,在儲存的過程可能會造成系統負擔。 ![](https://i.imgur.com/Jx86Q87.png) ![](https://i.imgur.com/V0qmQzT.png) ### 相關的模式有 1.命令模式 Command Patterns (Undo 處理) 2.反覆器(迭代)模式 Iterator Patterns (紀錄與取得先前的 State) ![](https://i.imgur.com/Z4t407l.png) 註: 與迭代模式一起用的時候,若迭代完成後刪除 State 發生例外時,有可能產生 Garbage,某些語言無法自動回收。解決方式可參考 (299)

    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