Shao-Huan,Lim
    • 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 New
    • 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 Note Insights 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

    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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    <!-- HackMD dark mode style template --> <!-- {%hackmd C-_zW0vxSXSSsOkJHknc8g %} --> ###### tags: `JS Design Pattern` 2/20 (二) Caesar === [創星物聯科技股份有限公司](https://www.104.com.tw/company/1a2x6bjgsv)徵才中,技術長歡迎您 簡報連結 --- ....更新中 目錄 --- [TOC] - 內心預期 - 團隊協作 - 作品展示 ## 基礎技術 > 如何取得入職門票? [frontend developer - roadmap](https://roadmap.sh/frontend) [backend developer - roadmap](https://roadmap.sh/backend) >基礎技術沒有學完的一天 - leetcode - js/php/python/kotlin/ruby/rust - ES2015/ES2021 ### 那麼 - 要如何學習目前的技術 - 要如何看待目前的技術 ### 三大框架差異,孰優孰劣 - vue - angular - react 學完之後知道個別的東西各有所長,哪些優化哪些簡化,哪些黑魔法都可以比較跟理解 ### 所以 - 如何學習未來的技術 - 如何看待未來的技術 - 如何學習未來的技術 - 如何看到外來的技術 ### 新的框架 > 並非很新,但尚未接觸過該項目,你會如何學習 - Svelte - Qwik - Elix ### 到底技術要學到什麼層面才可以呢? > 會動就好 V.S 為何會動 太極拳只重其意,不重其招,你忘記所有招式,就練會太極拳了 --- ## 建立模式 > 古典Design Patern > 主觀來說,非物件導向(OO)愛好者 主要還是在談這些古典 Design Pattern 的物件導向層面怎麼在 JS 裡面實用,但只談 物件導向(OO) 的層面只是 JS 設計模式的冰山一角 #### Everthing is Prototype JS 中的任何東西 create 之後就是 object,null跟undefine都是。 >methods is available inside __proto__,可以透過在瀏覽器的開發者模式查看 #### 閉包(Closure) 這樣才以從底層直接呼叫外層,從全域變數進行資料的加總,因為這樣才可以有辦法做 callback,在 scope variable 叫出回傳。若沒有closure就會變成undefine無法回傳 - Scope Variable - Global Context - Excution Contenxt ## 常見的設計模型 ### Singleton 不會重新initial,會是一個share instance,不會重新宣告 > 所以特別在哪裡啊?為什麼需要 Singleton? 若已經有實例存在,就不再重新初始化一個實例 #### 範例 - HTTP Client Instance 各個實作層共用一個 instance,就不需要一直初始化,可以共用 config(如 axios 實例,因為很多時候,前端只需要面對一個後端伺服器)。 ![image](https://hackmd.io/_uploads/r1Yg0WMnp.png) - SQL Client 只占用一個連線,不會佔用太多的CPU資源, ### Prototype >主要是擁有 share function 的好處 ```js const carPrototype = { startEngine() { console.log(`starting the engine of the ${this.year} ${this.model}!`); } }; function createCar(model, year) { let car = Object.create(carPrototype); car.model = model; car.year = year; return car; } const myCar = createCar('Tesla', 2022); console.log(myCar); // Inspect the car object myCar.startEngine(); ``` ![image](https://hackmd.io/_uploads/ByYU1fG36.png) 權限管理若有三個等級 admin, editor, reader, 就可以用這種方式來處理,就不用分別寫在分別三個地方。 #### 若一個東西重複三次以上,就可以做重構,不然真的會是bad smell(bad taste) ### Facade(法薩,法語念) >所有instance的聚合 ```js class PlumbingSystem{ setPressure(v: number){} turnOn(){} turnOff(){} } class ElectricalSystem{ setVoltage(v:number){} turnOn(){} turnOff(){} } class House { private plumbing = new PlumbingSystem() private electrical = new ElectricalSystem() public turnOnsystems(){ this.electrical.setVoltage(120); this.electrical.turnOn() this.plumbing.setPressure(500) this.plumbing.turnOn() } public ShutDown(){ this.plumbing.turnOff(); this.electrical.turnOff(); } } const client = new House() client.turnOnsystems() client.ShutDown() ``` 以遙控器為例,就可以拆分為:「開冷氣」、「開電視」、「全開」、「全關」等等 >將許多小型模組聚合 要定義並注意要包含的功能面向,避免成為「萬能遙控器」。 如果是「購買人」這個角色,既可以買東西又可以賣東西,有錢又有背包,且一直延伸下去,就可能會造成這個 Class 寫好幾千行 code。 ### Proxy 2019 之後才在 js 出現的東西,可以在用 proxy 做包裝,讓別人不會直接去對本來的物件做處理 這個的好處是可以透過 proxy 做改寫而不會直接去直接改寫物件。 ![image](https://hackmd.io/_uploads/SydmbGM2a.png) 最常想到的是 vue,reactive就是用 proxy 來做的 也可以使用在 cache 的實作,當作中間層來保護來源資料跟做一些儲存的任務,如 API 資料快取。 ![image](https://hackmd.io/_uploads/BkJ5Wzznp.png) 若有一些值不想給其他人所使用的話,就會這樣做這樣的東西 ```ts import {reactive} from 'vue'; const state = reactive{{ count: 0}} ``` ### Mixin 很常被用到的**功能集合**整理成 mixin 搖尾巴、玩球、叫一聲,這些能力,不只可以用在狗狗身上,也可以用在貓身上。 ```js class Dog { constructor(name){ this.name = name } } const dogFunctionality = { bark: () => console.log('woof'), wagTail: () => console.log("wagging my tail!") play: () => console.log("playing") } Object.assign(Dog.prototype, dogFunctionality) ``` ```js const pet1 = new Dog("Daisy"); pet1.name; //Daisy pet1.bark();// Woof pet1.play(); //Playing ``` 我們很常用的事 lodash mixin,用 lodash 本身來做新的 mixin 動作也有新的功能可以進來,那些常見或是專屬的功能就可以這樣放置。 ```js var _ =require('lodash'); var myMixins={ sayHello: function() { console.log('Hello'); } } _.mixin(myMixins); _.sayHellow(); // Hello ``` 擴充客製化的功能 ### Flyweight 使用一個 mapping list 來記錄購物車,每一個新增購物車的時候就使用 遊戲業大概比較常見,去實作很多很小的東西來重新處理 [example](https://www.oreilly.com/library/view/learning-javascript-design/9781449334840/ch09s18.html) ### Observer Vue 的 watch 可以視為 Observe Pattern 這東西可能不難寫,但要在哪裡實作? 有些購物車頁籤可以用session.storage也可以用observer來做實作 #### 用途 訂閱 通知 廣播 一對一 一對多的通知都可以做 ![image](https://hackmd.io/_uploads/BkUsNGf3a.png) 若真的太麻煩,就用 rxjs 吧~ ![image](https://hackmd.io/_uploads/S1ZqSMGn6.png) ### Mediator 元件邏輯互相耦合,可以解耦,改為大家都對中間者做行為 ![image](https://hackmd.io/_uploads/SkCoHff3p.png) express 的 middleware 就是這個模式,所有的處理先過中間層,再做對應的處理 ![image](https://hackmd.io/_uploads/r196Hzznp.png) ```js const app = require("express")(); app.use( "/", (req, res, next) => { req.headers["test-header"] = 1234; next(); }, (req, res, next) => { console.log(`Request has test header: ${!!req.headers["test-header"]}`); next(); } ); ``` ![image](https://hackmd.io/_uploads/HkYNUGGh6.png) 前端可以使用 postal 套件 ### 到底 Design Pattern 是什麼? ![upload_912ad928f9d4f02f1c7833c662c799c6](https://hackmd.io/_uploads/SyucK6M3T.png) 很多時候我們只知其實作,而不知其名。認識設計模式的名詞的過程,會帶來的好處是可以將自己原本建立的作法與設計與 Pattern 做連結,方便未來與別人交流溝通。如:這就是 Observer Pattern。 第七章只是剛開始,後面JS的pattern還有很多東西有關: - MVC - State Machine 了解所有招式之後,就忘記他吧,不要太在意名詞!記得就好,有印象就好 ## 小結 - 當你開始造輪子的時候你才會知道做輪子的人在想什麼 - 終其一生都在 CRUD,那這些東西都沒有用處 - 如果你都是在用別人做的東西的話,那可能不會用到這些;當你開始寫底層架構時,可能才會開始想要用什麼 Pattern 比較好,要用什麼演算法... - 如果你發現程式碼裡面,很多東西一直在重複,就可以想應該要怎麼抽象比較好 ![](https://kuro.tw/slides/js-design-pattern-00/assets/Tai-Chi-g_orBHBw.png)

    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