杜嘉豪
    • 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
    • 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
    • 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 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
  • 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
    DP5 抽象工廠、轉接器模式 === ###### tags: `DesignPatterns` # 抽象工廠模式 p.209 菜鳥工程師遇到問題,就只會用時間來擺平QQ ```C#= static void Main(string[] args) { User user = new User(); /* 1.su 被綁定在 SqlServerUser,當變化發生(出現抽換資料庫需求),就需要改動程式碼, 這時候就可以透過封裝變化解開耦合,讓 client 對資料庫的使用改為依賴於介面,而非直接依賴於某個資料庫 2. client 對於 user 的操作直接依賴於資料庫,應該依賴於一個 User 存取介面 */ SqlServerUser su = new SqlServerUser(); su.Insert(user); su.GetUser(1); Console.Read(); } class User { private int _id; public int ID { get {return _id;} set {_id = value;} } private string _name; public string Name { get {return _name;} set {_name = value;} } } class SqlServerUser { public void Insert (User user) { Console.WriteLine("Insert into user"); } public User GetUser(int id) { Console.WriteLine("Select * from user"); return null; } } ``` ```C#= static void Main(string[] args) { User user = new User(); Ifactory factory = new SqlServerFactory(); IUser iu = factroy.CreateUser(); iu.Insert(user); iu.GetUser(1); Console.Read(); } interface IUser { void Insert(User user); User GetUser(int id); } class SqlServerUser : IUser { public void Insert (User user) { Console.WriteLine("Insert into user"); } public User GetUser(int id) { Console.WriteLine("Select * from user"); return null; } } class AccessUser : IUser { public void Insert (User user) { Console.WriteLine("Insert into user"); } public User GetUser(int id) { Console.WriteLine("Select * from user"); return null; } } interface IFactory { IUser CreateUser(); } class SqlServerFactory: Ifactory { public IUser CreateUser() { return new SqlServerUser(); } } class AccessFactory: Ifactory { public IUser CreateUser() { return new AccessUser(); } } ``` 工廠模式 ![](https://i.imgur.com/NvVCsIO.png) ### 抽象工廠模式使用時機: 有很多資料庫,資料庫中有很多表。解決這種涉及多個產品系列的問題,就可以使用抽象工廠模式。 ![](https://i.imgur.com/kOEpoTl.png) ```C#= static void Main(string[] args) { User user = new User(); Department dept = new Department(); // Ifactory factory = new AccessFactory(); Ifactory factory = new SqlServerFactory(); IUser iu = factroy.CreateUser(); iu.Insert(user); iu.GetUser(1); IDepartment id = factroy.CreateDepartment(); id.Insert(dept); id.GetDepartment(1); Console.Read(); } ``` ## 定義 : ### 工廠模式 : 工廠方法模式是定義一個用於建立物件的介面,讓子類別決定實體化哪一個類別。 ### 抽象工廠 : 抽象工廠模式提供一個建立一系列相關或互相依賴物件的介面,而無須指定他們具體的類別。 ![](https://i.imgur.com/atsUY4z.png) #### 優點: 1. 便於交換產品系列,由於具體工廠類別在一個應用中只需一在初始化的時候出現一次,這就使的改變一個應用的具體工廠變得非常容易, 需要使用不同的產品設定時只需要改變具體的工廠即可。 p. 221 2. 抽象工廠讓具體的建立實體過程與用戶端分離,用戶端是透過他們都抽象介面操縱實體,產品的具體類別銘也被具體工廠的實現分離,不會出現在客戶端程式碼中。 p. 221 #### 缺點: 1. 以上圖為例,若要新增一個產品,則需在所有 Factory 中異動新增 method。 ### 使用簡單工廠改造抽象工廠可以避免新增產品需同時修改許多工廠的問題 透過使用簡單工廠,使用一個 DataAccess 類別,來去除 IFactory、SqlServerFactory、AccessFactory。 ![](https://i.imgur.com/8w924BT.png) ```C#= class DataAccess { // private static readonly string db = "sqlServer"; private static readonly string db = "accessServer"; // 用戶端就不用知道是哪種 DB 達到解偶的目的(p.225) public static IUser CreateUser() { IUser result = null; switch (db) { case "SqlServer": result = new SqlServerUser(); break; case "Access": result = new AccessUser(); break; } return result; } public static IDepartment CreateDepartment() { IDepartment result = null; switch (db) { case "SqlServer": result = new SqlServerDepartment(); break; case "Access": result = new AccessDepartment(); break; } return result; } } //client static void Main(string[] args) { User user = new User(); Department dept = new Department(); // Ifactory factory = new AccessFactory(); // Ifactory factory = new SqlServerFactory(); //IUser iu = factroy.CreateUser(); // 直接得到實際的資料庫存取實體,而不存在任何依賴 IUser iu = DataAccess.CreateUser(); iu.Insert(user); iu.GetUser(1); //IDepartment id = factroy.CreateDepartment(); IDepartment id = DataAccess.CreateDepartment(); id.Insert(dept); id.GetDepartment(1); Console.Read(); } ``` ## 使用簡單工廠+抽象工廠的問題: Q : 當今天要新增 Oracel 資料庫時,需要在 DataAccess類別中的每一個方法新增對應 switch case。如何能做到動態的自動選擇對應的資料庫? A : IoC(Inversion of Control 控制反轉) + DI(Dependency Injection 依賴注入) ```C#= using System.Reflection; class DataAccess { private static readonly string AssemblyName = "Abstract Factory"; private static readOnly string db = CongigurationManager.AppSetting['DB']; public static IUser CreateUser() { string className = AssmblayName + "." + db + "User"; // SqlServerUser、OracleUser return (IUser)Assembly.Load(AssemblyName).CreateInstance(className) } public static IDepartment CreateDepartment() { string className = AssmblayName + "." + db + "Department"; return (IDepartment)Assembly.Load(AssemblyName).CreateInstance(className) } } ``` ### 所有應用簡單工廠的地方,都可以考慮用反射技術來去除 switch、 if 陳述,解除分之判斷帶來的耦合 (p.229) [Laravel 服务容器,IoC,DI](https://learnku.com/articles/19195) [Laravel如何實現依賴性注入?](https://medium.com/mr-efacani-teatime/laravel%E5%A6%82%E4%BD%95%E5%AF%A6%E7%8F%BE%E4%BE%9D%E8%B3%B4%E6%80%A7%E6%B3%A8%E5%85%A5-d760c8e5abde) [如何理解LARAVEL 的IOC容器](http://blog.twbryce.com/%E5%A6%82%E4%BD%95%E7%90%86%E8%A7%A3laravel-%E7%9A%84ioc-%E5%AE%B9%E5%99%A8/) ---- ``` @startuml interface IUser { } class SqlServerUser { } class AccessUser { } IUser <|.. SqlServerUser IUser <|.. AccessUser interface IDepartment { } class SqlServerDepartment { } class AccessDepartment { } IDepartment <|.. SqlServerDepartment IDepartment <|.. AccessDepartment class DataAccess { - db:string + CreateUser() : IUser + CreateDepartment() : IDepartment } DataAccess ..> IUser DataAccess ..> IDepartment @enduml ``` ``` @startuml interface IUser { } class SqlServerUser { } class AccessUser { } IUser <|.. SqlServerUser IUser <|.. AccessUser interface IDepartment { } class SqlServerDepartment { } class AccessDepartment { } IDepartment <|.. SqlServerDepartment IDepartment <|.. AccessDepartment interface IFactory { +CreateUser() +CreateDepartment() } class SqlServerFactory { +CreateUser() +CreateDepartment() } class AccessFactory { +CreateUser() +CreateDepartment() } IFactory <|.. SqlServerFactory IFactory <|.. AccessFactory SqlServerFactory ..> SqlServerUser AccessFactory ..> AccessUser SqlServerFactory ..> SqlServerDepartment AccessFactory ..> AccessDepartment @enduml ``` # 轉接器模式 定義:轉接器模式,將一個類別的界面轉換成客戶希望的應外一個界面。 轉接器模式使得原本由於界面不相容而不能一起工作的那些類別可以一起工作。 。 p.252 系統的資料和行為都正確,但界面不符時,我們應該考慮用轉接器,目的是使控制為之外的一個原有物件與某個界面匹配。轉接器模式主要應用於希望複用一些既有的類別,但是界面又與複用環境要求不一致的情況,比如在需要對早期程式碼複用一些功能等應用上很有實際價值。 類別轉接器:透過多承繼成對一個界面與另一個界面進行匹配 物件轉接器 p.254 何時使用轉接器模式?想使用一個已存在的類別,但如果他的界面,也就是他的方法和你要求的不相同時,就應該考慮用轉接器模式 因為兩個類別所做的事情相同或相似,但是具有不同的界面時要使用他。由於類別都共用同一個界面,客戶端就可以統一調用同一個界面。 p.254 1.只有在雙方都不太容易修改時,在使用轉接器模式轉接(針對老舊程式碼,否則初期規劃應可避免) 2.串接第三方元件,沒必要為了第三方改變我方界面,這時也可以可慮使用 [What is the difference between the Facade and Adapter Pattern?](https://stackoverflow.com/questions/2961307/what-is-the-difference-between-the-facade-and-adapter-pattern/2961400) Adapter == making a square peg fit into a round hole. Facade == a single control panel to run all the internal components. [Facade Pattern - WIKI](https://en.wikipedia.org/wiki/Facade_pattern) "An Adapter is used when the wrapper must respect a particular interface and must support a polymorphic behavior. On the other hand, a facade is used when one wants an easier or simpler interface to work with."

    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