Try   HackMD

Observer Pattern

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Terms

(1). 主題、對象、目標 Subject -> 被(大眾)觀察的對象、名人

(2). 觀察者、訂閱者 Observer, Subscriber

(3). 觀察者 如何跟 主題 產生連結,開啟小鈴鐺「訂閱(Subscribe)」

​​​​觀察者選擇有興趣的主題進行訂閱
​​​​* Ken 訂閱 JavaScript Weekly 
​​​​* Ken 追蹤 PJCHENder網頁開發咩腳

(4). 名人藉由通知(Notify),將新訊息傳給訂閱者

​​​​* JavaScript Weekly 每週都會發新文章連結到 Ken 的信箱

1. Observers subscribe subjects

2. Subjects notify observers

3. 訂閱之後就能自動收到更新、通知 -> Observer Pattern


使用時機:某特定事件發生了,我想要對此作出反應

按鈕 (+) 被點擊了,我想要把變數 count + 1

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

不使用 Observer Pattern

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Observer Pattern的優缺點

優點

  1. 降低目標與觀察者間的耦合關係,兩者之間為抽象耦合關係。
  2. 目標與觀察者間建立了一套觸發機制。

缺點

  1. 目標與觀察者間的依賴並無完全切除。
  2. 當觀察者物件多時,會影響效能。

Observer Pattern的使用時機

  1. 物件之間存在一對多的關係,一個物件狀態改變會影響其他物件時。

ref: https://ianjustin39.github.io/ianlife/design-pattern/observer-pattern/

參考文章