Kai Chen
    • 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

      This note has no invitees

    • 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
    • Note Insights
    • 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 Note Insights 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

    This note has no invitees

  • 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
    # 虎年行大運 - Design Pattern - Strategy ## 前言 在生活中,一定都有遇過目的一樣,但過程總會有些許不同的事情。 以買菜這件事情而言,去傳統市場買?去零售超市買?去量販店買?都是買菜,但是過程卻可能不同。 傳統市場和零售超市可能在家附近,量販店可能就要驅車前往。而在價格部份則可能量販店較便宜。 類同上述目的相同、過程不同的事情百百種。程式設計也相同,若完成需求的程式邏輯簡單,那真的也不需要參考設計模式的方式設計,但工程師們就是專門處理複雜問題,化繁為簡的職業。你面對的問題絕不簡單,你必須要學會可以正確切分程式邏輯的設計模式。 今天要介紹的就是 **Strategy Pattern** ## 主題 **Strategy Pattern** 中文常見名稱 **策略模式** 屬於 Behaviral Patterns 一種,目的是為了封裝演算法,達到流程與演算法的解偶,後續流程可以透過引用不同的演算法物件,取得不同的演算法內容進行需求的處理,並產出相同的結果。 引用上述的買菜例子,我們可封裝三種買菜的過程與方式,而最終都會取到買菜的結果。 使用者專注於結果的取得與後續的處理。專注於業務邏輯層。 開發者則可專注於產生結果的過程與方式。專注於應用模組層。 彼此在工作結構上可以切分得更仔細,專注於各自擅長的領域。 **優點:** - 高度靈活替換實體類別,避免大量使用 If Else - 水平擴展容易 **缺點:** - 垂直擴展困難 - 使用者必須熟知所有策略實體類別 ![](https://i.imgur.com/fD9fJgp.png) *[該圖引用來自 Wiki Strategy Pattern - Class Diagram](https://en.wikipedia.org/wiki/Strategy_pattern)* ## 實行方式 ```java= package designPattern.Strategy; /** * @author kaichen * Strategy 模式,將不同的處理行為或邏輯進行封裝,並藉由介面提供接口方法。 * 由外界決定實現的實體 */ public class Strategy { public static void main(String [] args){ InitAbstractStrategy initStrategy = new InitStrategyImpl(); initStrategy.doPay(); InitAbstractStrategy initStrategy2 = new InitStrategyImpl2(); initStrategy2.doPay(); } } interface InitStrategy { public void pay(); public void beforePay(); public void afterPay(); } abstract class InitAbstractStrategy implements InitStrategy { public void doPay(){ beforePay(); pay(); afterPay(); } } class InitStrategyImpl extends InitAbstractStrategy { @Override public void pay() { System.out.println("This is Impl 1 Pay()"); } @Override public void beforePay() { System.out.println("This is Impl 1 beforePay()"); } @Override public void afterPay() { System.out.println("This is Impl 1 afterPay()"); } } class InitStrategyImpl2 extends InitAbstractStrategy { @Override public void pay() { System.out.println("This is Impl 2 Pay()"); } @Override public void beforePay() { System.out.println("This is Impl 2 beforePay()"); } @Override public void afterPay() { System.out.println("This is Impl 2 afterPay()"); } } ``` 在範例中建立 **InitStrategy** 的介面,並以 **InitAbstractStrategy** 抽象實作介面後,在抽象建立流程方法,以便流程與方法的解耦合。 隨後建立 **InitStrategyImpl** 與 **InitStrategyImpl2** 等兩個實體,並繼承抽象 **InitAbstractStrategy**,實作介面方法。 呼叫時候透過抽象呼叫實體,我們即可直接使用抽象的流程方法,讓介面負責接口、抽象負責流程、實體負責實作。 總結: - 介面: 提供接口 - 抽象: 制定流程 - 實體: 實作邏輯 以上述這種方式去處理這一次的範例程式結構。 :::danger 用一句話介紹 Strategy Pattern: **將不同面向的處理模組進行抽出,獨立於流程之外,達到兩者職責分明的設計模式** ::: 首頁 [Kai 個人技術 Hackmd](/2G-RoB0QTrKzkftH2uLueA) ###### tags: `Design Pattern`

    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