Kimn
    • 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
    • Make a copy
    • 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 Make a copy 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
    --- ###### tags: `Design Pattern` --- # 10/26 ## 設計模式 ### 概述 - GoF23 23 種設計模式 - 代碼設計 ==經驗總結== ,解決特定問題的一系列套路, - 必要性:物件導向的 實際應用 - 標準化、工程化 ### 分類 - 創建型模式 用於描述 如何創建物件,主要特點 將物件的 ==創建與使用分離== (解耦) :::info 單例、原型、工廠方法、抽象工廠、建造者 等5種 ::: - 結構型模式 用於描述將類或物件按 ==某種佈局== 組成更大的結構, 好比買蓋房材料,要用這些材料搭建起整個房屋的架構 :::info 代理、適配器、橋接、裝飾、外觀、享元、組合 等7種 ::: - 行為型模式 用於描述類或物件之間==如何互相協作==,完成單個物件無法單獨完成的任務,以及==如何分配職責== :::info 模板方法、策略、命令、職責鏈、狀態、觀察者、中介者、迭代器、訪問者、備忘錄、解釋器 等 11 種 ::: ### UML - 統一建模語言,是用來設計軟體的可視化建模語言, - 特點是簡單 統一 圖形化,能表達軟體中的動態與靜態訊息 - UML從目標系統的不同角度出發,定義了 - 用例圖 類圖 物件圖 狀態圖 活動圖 時序圖 協作圖 構建圖 部署圖 等9種 ### 類圖 - 類圖是顯示了模型的==靜態結構==,特別是模型中存在的類,類的內部結構以及他們==與其他類的關係==等 - 類圖不顯示暫時性訊息,是物件導向建模的主要組成部分 - 作用:提供靜態結構圖,描述了系統的類集合,屬性和類之間的關係,簡化了人們對系統的理解 - 類圖是系統分析與==設計階段==的重要產物,是系統編碼與測試的重要模型 - 表示方式 +:public 、 -:private 、 #:protected ![](https://i.imgur.com/GM64kmi.png) - 關聯關係 - 聚合關係 強關聯 整體和部分之間 - 實現關係 ![](https://i.imgur.com/RphyzqN.png) ## 軟體設計原則 - 開閉 里氏代換 依賴反轉 接口隔離 迪米特 合成復用原則 ### 開閉原則: - ==擴展開放,修改封閉==:在程式需要擴充的時候,不能去修改原有的代碼,實現==熱插拔==的效果 - 想要達到這種效果,需要使用介面和抽象類 - 以 skin 例子:定義抽象類 skin,基礎版 高級 黃金版..等等都是其子類,滿足開閉原則 ![](https://i.imgur.com/rmMLYa1.png) ```java= // 定義抽象類 public abstract class AbstractSkin { // 顯示方法 public abstract void display(); } // 兩種皮膚 public class DefaultSkin extends AbstractSkin { @Override public void display(){ System.out.println("默認皮膚"); } } public class OtherSkin extends AbstractSkin{ @Override public void display() { System.out.println("新皮膚"); } } // 輸入法 有皮膚 public class Input { private AbstractSkin skin; public void setSkin(AbstractSkin skin) { this.skin = skin; } public void display(){ skin.display(); } } // 實作 達成開閉原則 public class Client { public static void main(String[] args) { // 創建輸入法物件 Input input = new Input(); // 創建皮膚物件 //DefaultSkin skin = new DefaultSkin(); OtherSkin skin = new OtherSkin(); // 將皮膚設置到輸入法中 input.setSkin(skin); // 顯示皮膚 input.display(); } } ``` ### 里氏代換原則 - 子類可以擴展父類的功能,但不能改變父類原有的功能 - 子類繼承父類時,除了添加新的方法完成新增功能外,盡量不要不要重寫父類的方法 - 經典案例:==正方形不是長方形== ![](https://i.imgur.com/RPujbqh.png) ```java= // 長方形類 public class Rectangle { private double length; private double width; } // 正方形類 public class Square extends Rectangle { @Override public void setLength(double length) { super.setLength(length); super.setWidth(length); } @Override public void setWidth(double width) { super.setLength(width); super.setWidth(width); } } ``` ```java= public class RectangleDemo { // 拓寬方法 public static void resize(Rectangle rectangle) { // 判斷寬如果比長小,進行拓寬的操作 while (rectangle.getWidth() <= rectangle.getLength()) { rectangle.setWidth(rectangle.getWidth() + 1); } } // 印出長和寬 public static void printLengthAndWidth(Rectangle rectangle) { System.out.println(rectangle.getLength()); System.out.println(rectangle.getWidth()); } public static void main(String[] args) { // 創建長方形物件 Rectangle r = new Rectangle(); r.setLength(20); r.setWidth(10); // 調用 resize 方法進行拓寬 resize(r); printLengthAndWidth(r); System.out.println("------分隔線------"); // 創建正方形物件 Square s = new Square(); s.setLength(10); // 調用 resize 方法進行拓寬 - 這段會不斷執行造成錯誤 resize(s); printLengthAndWidth(s); } } ``` :::danger 結論:在 resize 方法中,長方形類的參數不能被正方形所代替,如果進行替換就得不到預期的結果,因此 長方形和正方形之間 違反里氏代換原則 ::: :::info - 如何改進?此時我們需要重新設計他們之間的關係 - 抽象出一個四邊形介面,讓長方形和正方形實現四邊形介面 ::: ![](https://i.imgur.com/6WIqiCk.png) ```java= // 四邊形介面 public interface Quadrilateral { double getLength(); double getWidth(); } // 正方形類 public class Square implements Quadrilateral { private double side; public double getSide() { return side; } public void setSide(double side) { this.side = side; } } // 長方形類 public class Rectangle implements Quadrilateral { private double length; private double width; public void setLength(double length) { this.length = length; } public void setWidth(double width) { this.width = width; } } ``` ```java= public class RectangleDemo { // 拓寬方法 public static void resize(Rectangle rectangle) { // 判斷寬如果比長小,進行拓寬的操作 while (rectangle.getWidth() <= rectangle.getLength()) { rectangle.setWidth(rectangle.getWidth() + 1); } } // 印出長和寬 public static void printLengthAndWidth(Quadrilateral quadrilateral) { System.out.println(quadrilateral.getLength()); System.out.println(quadrilateral.getWidth()); } public static void main(String[] args) { // 創建長方形物件 Rectangle r = new Rectangle(); r.setLength(20); r.setWidth(10); // 調用 resize 方法進行拓寬 resize(r); printLengthAndWidth(r); System.out.println("------分隔線------"); // 創建正方形物件 Square s = new Square(); s.setSide(10); //resize(s); --- 只有長方形可以調用 printLengthAndWidth(s); } } ``` :::success resize 只有長方形可以調用,解決問題 :::

    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