ModernWeb
      • 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
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners 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
    • 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 Help
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
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners 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 Patterns / 翁菁美 (Nina) {%hackmd @ModernWeb/SyA2U6SmT %} > 共筆請從這開始 ## Design Pattern Design Pattern Gof ![](https://circle.visual-paradigm.com/wp-content/uploads/2017/08/GoF-Design-Patterns-Catalog.png) ## 瓶蓋工廠案例 ### 單例模式 (Singleton pattern) - 分類: 創建型模式 - 動機: 對於一些類別來說,只有一個實體才是合理的 - 意圖: 保證一個類別只有一個實體,並提供一個訪問他的全局訪問點 - 優點: - 確定一個類別只有一個實體 - 該實體在全域都可以防問 - 缺點: - 全域都可訪問,易造成錯綜復雜的關係 - 依賴同一個實體,可能會造成測試不易 範例: ```typescript export class BottleCapFactory { constuctor(){} createBottleCap(){} } ``` ```typescript export class TaipeiBottleCapFactory { constuctor(){} private static getIntsance(){ return this; } getInstance(){} createBottleCap(){ } } ``` ```typescript // how to call it?(有人能補這邊嗎?剛好像說到不能 new? ) import TaipeiBottleCapFactory from ... ``` ```typescript let isLoading = false; const loader = { show:()=>{ isLoading = true; return isLoadding; }, hide: () => { isLoading = false; return isLoadding; } } Object.freeze(loader); export { loader }; ``` Object.freeze() 靜態方法凍結物件。 凍結物件會阻止擴充功能並使現有屬性不可寫和不可配置。 凍結的物件無法再變更:無法新增屬性,無法刪除現有屬性,無法變更其可枚舉性、可配置性、可寫性或值,且無法重新指派物件的原型。 freeze() 傳回與傳入的物件相同的物件。 ### 工廠模式 (Factory pattern) - 分類: 創建型模式 - 動機: 根據條件會創建不同的實體 - 意圖: 創建實體時,實體的創建規則由工廠決定,創建者只需呼叫工廠創建實體即可,創建者不需知道創建規則細節。 - 優點: - 符合單一職責原則 - 符合開放封閉原則 - 避免了創建者和產品之間的緊密耦合 - 缺點: - 在一定程度上增加了系統複雜度 範例: ```typescript import {CapImageEnum} from "./capImageEnum"; export interface ``` ```typescript import {CapImageEnum} from './capImageEnum' import {IBottleFactory} from './' export class ... implemnt ... ``` ```typescript import factory from './...' factory.createBottleCap(CapImageEnum.IMAGE_A) factory.createBottleCap(CapImageEnum.IMAGE_B) ``` #### 前端應用 - UI component => 傳入不同 status ```jsx function Button({color='blue', text=''}){ return ( <button type='button' style={{backgroundColor: color}}> {text} </button> ) } <Button color='green' text='accept' /> <Button color='gray' text='cancel' /> ``` ### 觀察者模式 (Observer pattern) - 分類: 行為模式(Behavioral Pattern) - 動機: 當一個物件的狀態變更也需要一起更新別的物件的時候 - 意圖: 透過訂閱來收到正在觀察的物件所發生的事件 - 優點: - 符合開放封閉原則 - 缺點: - 如果觀察者和被觀察者之間有互相循環調用的話,會增加系統的複雜度 範例: ```typescript export interface IBserver { ... } ``` ```typescript import { IBserver} export class Subject { private oberservers: IBserver[] = []; public register(){} public unregister(){} public notifyAllObservers(){} } ``` ```javascript // 將 factory 加入監聽 factory.createBottleCap() // respones: 已建造完成 ``` #### 前端應用 EventListener IntersetionObserver #### 策略模式 (Strategy pattern) - 分類: 行為模式(Behavioral Pattern) - 動機: 有不同的選擇 - 意圖: 將不同的邏輯各自封裝起來,並且使他們可以互相交替 - 優點: - 符合開放封閉原則 - 將演算法的實作細節與使用該演算法的程式碼隔離 - 缺點: - 策略類別增加,一定程度增加系統複雜度 範例: impletment 時選擇不同組合/值 ``` const factoryTaipei =. new BCfactory(new ProductADesignStragtegy) factoryTaipei.createBottleCap() // image A, Small ``` #### 前端應用 sorting // 但我不是很懂這個策略模式有什麼關係? --- >聊天室 >簡報好用心,用瓶蓋工廠舉例 >不要緊張 >卡哇伊~~ >XD >design patterns 很重要,面試時常提問用過那一些dp 但很多人都答不出來。 >~~看到 dp 會以為是 dynamic programming~~ >loadding 是 typo 嗎 >筆記已經往下模板都長好了,也太強XD Q:工廠模式是不是就像reusable component? >正確, reusable component 就是使用工廠模式 design Q:工廠模式和 adapter pattern 差別是什麼嗎? Q:怎麼感覺工廠模式跟策略模式也很像? 缺點好像都很類似 都是增加系統複雜度XD > 正好相反,設計模式都是為了減低系統的複雜度而衍生的 設計模式本身就是會增加複雜度吧,但這個複雜度是有公約的,所以可能會比單純不斷直線型思考寫 code 好維護一點 工廠模式、適配器模式以及策略模式都是軟體設計中為了解決特定問題而產生的模式。在學習這些模式之前,理解它們背後的設計理念和應對的問題場景是非常重要的。由於不同的問題領域可能存在一定的交集,因此在介紹時可能會給人一種它們使用上似乎很相似的錯覺。但實際上,每種模式都有其獨特的應用情境和解決問題的方式。 具體來說,工廠模式主要用於創建對象時抽象創建過程,使得客戶端不需要知道具體的實現類,只需關心所需對象的接口。適配器模式則是用來解決接口不兼容的問題,它允許將一個類的接口轉換成客戶端期待的另一種接口。策略模式是一種使得算法可以在運行時獨立於客戶端的變更,提供了管理相關的算法族的方法。 這些模式之間的差異並不總是一目瞭然,但是透過深入分析它們的結構和意圖,我們可以更精確地選擇在合適的場合使用適當的模式。在教學時,演講者應當致力於更清晰地闡述這些模式的獨特性和適用範圍,而不應該僅僅通過展示代碼來傳達它們的概念。

    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