Design Pattern
  • Introduction
  • Chapter1: MVVM
  • Chapter2: 觀察者模式 (Observer Pattern)
  • Chapter3: 策略模式 (Strategy Pattern)
  • Chapter4: 單例/獨體模式 (Singleton)
  • Chapter5: 裝飾者模式 (Decorater Pattern)
  • Chapter6: 命令模式 (Command Pattern)
  • Chapter7: MVC
Powered by GitBook
On this page
  • This section contain the following items:
  • 1.Singleton Pattern
  • 2.Singleton Pattern Example for javascript
  • 3.Singleton Pattern Example for C#

Was this helpful?

Chapter4: 單例/獨體模式 (Singleton)

PreviousChapter3: 策略模式 (Strategy Pattern)NextChapter5: 裝飾者模式 (Decorater Pattern)

Last updated 5 years ago

Was this helpful?

This section contain the following items:

  • 1.Singleton Pattern

  • 2.Singleton Pattern Example for javascript

  • 3.Singleton Pattern Example for C#

1.Singleton Pattern

  • 單例/獨體模式的核心概念

    • 滿足以下兩個條件

      • 1.提供一個全域的存取點(access point)

      • 2.一個類別只會有一個實例

  • 單例/獨體模式所要解決的問題(痛點)

    • 以javascript為例

      • 問題與挑戰

        • 例如瀏覽器中的windows物件, 或是設計只出現一次彈跳視窗, 執行續池, 全域快取等

      • 1.建立一個單例物件

        • 封裝成可以使用new建構子來建立單例物件

      • 2.惰性單例

        • 載入時就建立, 每次使用時判斷是否instance已存在 -> 按按鈕才會建立實體, 每次使用時判斷是否instance已存在 -> 將獨體邏輯與建立邏輯分開來

      • 3.封裝私有變數

        • 為了不讓全域變數污染, 或讓其污染降到最低, 可以封裝起來

  • 以C#為例

    • Class Diagram

      • 只有getInstance()一個函式, 而且沒有公開的建構子

    • 問題與挑戰

      • 多執行緒時的同步問題與效能問題

2.Singleton Pattern Example for javascript

3.Singleton Pattern Example for C#