學什麼,寫什麼。
    • 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 No publishing access yet

      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.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      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 No publishing access yet

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    # 2. Factory Method ###### tags: `DesignPatterns` ## 關於 Factory Method 本篇將討論以下幾個問題 > ### 1. 關於 Factory Method > ### 2. UML > ### 3. 將 UML 轉為程式碼 > ### 4. 情境 > ### 5. Simple Factory --- ## 測試環境: >OS:Windows 10 >IDE:Visual Studio 2019 --- ## 1. 關於 Factory Method > Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. > > by [Gang of Four](https://en.wikipedia.org/wiki/Design_Patterns) - 定義用來創建物件的介面,但實例化哪個類別由子類別決定 - 工廠方法將實例化延遲至子類別 Factory Method(工廠方法)屬於創建型(Creational Patterns),當遇到需要**依靠多個 if/else 來判斷創建哪個實體**時,使用 Factory Method 來將依據需求取得相對應實體的這個部分抽象化,由於外部不需要了解取得實體的細節,使得相依減低,進而達到高內聚低耦合的目的。 優點: - 符合 單一職責原則(Single Responsibility Principle) - 符合 開閉原則(Open Closed Principle) (Simple Factory 不符合) 缺點: - 會增加許多 class 造成程式複雜度增加 --- ## 2. UML ![](https://i.imgur.com/VcEuSCx.jpg) Class 間關聯: - ConcreteProduct 繼承 Product - ConcreteCreator 繼承 Creator - ConcreteCreator 依賴 ConcreteProduct Class: - Product:處理邏輯的抽象類別或介面 - ConcreteProduct:處理邏輯的實作 - Creator:工廠方法的抽象類別或介面 - ConcreteCreator:工廠方法的實作,用來創建處理邏輯的實體 --- ## 3. 將 UML 轉為程式碼 開始之前先說明一下,UML 上雖然是以子類別繼承父類別來標示關聯,但範例中沒有多層繼承關係,且平常 interface 使用 DI 較為方便,C# 8.0 已支援預設實作([MSDN](https://docs.microsoft.com/zh-tw/dotnet/csharp/tutorials/default-interface-methods-versions)),所以在**範例程式碼的撰寫上都會盡量以 interface 取代 abstract class**。 ConcreteProduct A / B 皆實作 IProduct 介面 ```C# /// <summary> /// 處理邏輯的介面 /// </summary> public interface IProduct { } /// <summary> /// 處理邏輯的實作 A /// </summary> public class ConcreteProductA : IProduct { } /// <summary> /// 處理邏輯的實作 B /// </summary> public class ConcreteProductB : IProduct { } ``` 工廠方法的介面 ```C# /// <summary> /// 工廠方法的介面 /// </summary> public interface ICreator { public IProduct FactoryMethod(); } ``` ConcreteCreator A / B 皆實作 ICreator 介面 ```C# /// <summary> /// 工廠方法的實作 A /// </summary> public class ConcreteCreatorA : ICreator { public IProduct FactoryMethod() { return new ConcreteProductA(); } } /// <summary> /// 工廠方法的實作 B /// </summary> public class ConcreteCreatorB : ICreator { public IProduct FactoryMethod() { return new ConcreteProductB(); } } ``` 1. 透過`creator.FactoryMethod()`取得`product`實體 ```C# static void Main(string[] args) { var creators = new List<ICreator> { new ConcreteCreatorA(), new ConcreteCreatorB() }; foreach (var creator in creators) { IProduct product = creator.FactoryMethod(); Console.WriteLine($"Created {product.GetType().Name}"); } Console.ReadLine(); } ``` 執行結果 ```Console Created ConcreteProductA Created ConcreteProductB ``` --- ## 4. 情境 我們接到了一個付款的需求 - 需要能支援現有的兩種付款方式(現金、ApplePay) - 且未來可能會有更多不同的付款方式 付款介面 ```C# /// <summary> /// 付款介面 /// </summary> public interface IPayment { string Pay(int amount); } ``` 現金付款 & ApplePay 付款實作 ```C# /// <summary> /// 實作以現金付款 /// </summary> public class Cash : IPayment { public string Pay(int amount) { return $"使用 現金 付款 {amount} 元"; } } /// <summary> /// 實作以 ApplePay 付款 /// </summary> public class ApplePay : IPayment { public string Pay(int amount) { return $"使用 ApplePay 付款 {amount} 元"; } } ``` 工廠介面 ```C# /// <summary> /// 工廠介面 /// </summary> public interface ICreator_Payment { public IPayment FactoryMethod(); } ``` 實作工廠方法回傳付款實體 ```C# /// <summary> /// 實作工廠介面回傳現金付款實體 /// </summary> public class Creator_Cash : ICreator_Payment { public IPayment FactoryMethod() { return new Cash(); } } /// <summary> /// 實作工廠介面回傳 ApplePay 付款實體 /// </summary> public class Creator_ApplePay : ICreator_Payment { public IPayment FactoryMethod() { return new ApplePay(); } } ``` 1. 透過`creator.FactoryMethod()`取得付款實體 ```C# static void Main(string[] args) { var creators = new List<ICreator_Payment> { new Creator_Cash(), new Creator_ApplePay() }; foreach (var creator in creators) { IPayment payment = creator.FactoryMethod(); Console.WriteLine($"{payment.Pay(10)}"); } Console.ReadLine(); } ``` 執行結果 ```Console 使用 現金 付款 10 元 使用 ApplePay 付款 10 元 ``` --- ## 5. Simple Factory 簡單工廠方法屬於工廠方法的特例,並不包含在四人幫(Gang of Four, GoF)的設計模式之中 同樣使用上面付款的例子,不過將取得付款實體的方式改為靜態方法以 Switch 或是 if/else 來實作 Simple Factory 實作簡單工廠方法回傳付款實體 ```C# /// <summary> /// 簡單工廠方法 /// </summary> /// <param name="payType"></param> /// <returns></returns> public static IPayment GetPayment(PayType payType) { return payType switch { PayType.Cash => new Cash(), PayType.ApplePay => new ApplePay(), _ => null }; } ``` 1. 透過`SimpleFactory.GetPayment()`取得付款實體 ```C# static void Main(string[] args) { foreach (SimpleFactory.PayType payType in Enum.GetValues(typeof(SimpleFactory.PayType))) { SimpleFactory.IPayment payment = SimpleFactory.GetPayment(payType); Console.WriteLine($"{payment.Pay(10)}"); } Console.ReadLine(); } ``` 執行結果 ```Console 使用 現金 付款 10 元 使用 ApplePay 付款 10 元 ``` --- ## 完整程式碼 GitHub:[Creational_01_FactoryMethod](https://github.com/darionnnnnn/blog/tree/master/Blog/Creational_01_FactoryMethod) --- ## 總結 ### 本系列將 Factory Method 放在第一篇主要是因為想將 Factory Method 與 Abstract Factory 接連著說明,且由 Factory Method 開始理解起來較為容易,所以並未照著 [Design Patterns](https://en.wikipedia.org/wiki/Design_Patterns) 書中的順序。 ### 希望能藉由情境說明的方式加深對於 Design Pattern 的理解 & 印象,且能在遇到類似需求時能聯想到併套用於實際開發中。 --- ## 參考資料 1. [Design Patterns](https://en.wikipedia.org/wiki/Design_Patterns) 2. [大話設計模式](https://www.tenlong.com.tw/products/9789866761799) 2. [dofactory](https://www.dofactory.com/) 3. [Refactoring.Guru](https://refactoring.guru/) --- ## 新手上路,若有錯誤還請告知,謝謝

    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
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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