OOP Design (Head First Design Patterns) 学习笔记--03 Observer Pattern

Observer Pattern

Publishers + Subscribers = Observer Pattern

We call the publisher the SUBJECT, and the subscribers the OBSERVERS.

The Observer Pattern defines a one-to-many dependency between objects to that when one object changes state, all of its dependents are notified and updated automatically.


The power of Loose Coupling

When two objects are loosely couples, they can interact but have very little knowledge of each other. 

The Observer Pattern provides an object design where subjects and observers are loosely coupled. 

Why?

  • The only thing the subject knows about an observer is that it implements a certain interface (the Observer interface).
  • We can add new observers at any time. 
  • We never need to modify the subject to add new types of observers.
  • We can reuse subjects or observers independently of each other.
  • Changes to either the subject or an observer will not affect the other.
Design Principle:
Strive for loosely coupled designs between objects that interact.

Loosely coupled designs allow us to build flexible OO systems that can handle change because they minimize the interdependency between objects.

How Java's built-in Observer Pattern works
For an object to become an observer...
call addObserver() on any observable object
remove yourself as an observer just call deleteObserver()
For the Observerable to send notifications...
First of all you need to be Observable by extending the java.util.Observable superclass.
1. You first much call the setChanged() method to signify that the state has changed in your object.
2. Then call one of two notifyObservers() methods: either notifyObservers() or notifyObservers(object arg)
For an Observer to receive notifications...
  update(Observable o, Object arg)

Tools for your Design Toolbox
- OO Principles
Strive for loosely coupled designs between objects that interact.

- OO Patterns
Observer - defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值