The Observer Design Pattern

 
Observer Design Pattern
Observer Design Pattern
 
 
 
Observer Design Pattern
 
Define a one-to-many dependency between objects so that when one object changes state, all
its dependents are notified and updated automatically.
 
When to use the observer pattern
 
When you need many other objects to receive an update when another object changes
 
Examples in Games:
 
Notifying a quest module that
certain events have happened that
lead towards quest completion
 
Notifying UI elements that game state
has changed and thus health bar or
other needs to be updated immediately
 
Structure Of Observer
 
Events vs. Polling
 
 
Events vs. Polling
 
Polling
 
 A software design pattern (using “design pattern” a bit loosely
here) in which a process repeatedly checks another entity for a status
change.
 
Examples
:
 
- Keep pinging a server to make sure a connection stays alive
 
- Every 10 ms, check the printer for readiness
 
- In a game, check every frame whether the player incapacitated
 
*Often used in low-level programming (more so than high level)
 
Polling Example
Button
Main Application
Button
Button
Button
 
Were you clicked?
 
Nah
 
Were you clicked?
 
Nah
 
Were you clicked?
 
Yep!!!!!
 
Events vs. Polling
 
Events
 A software design pattern in which a process waits patiently
for an event of interest to occur and only reacts when necessary.
 
Examples
:
 
- Server, tell me when you are ready to connect
 
- Printer, let me know when you are ready to print
 
- Game over screen waits to be notified that player is dead
 
*Important: is NOT implemented using polling.
 
Events Example
Button
Main Application
Button
 
Let me know when
you get clicked, k?
 
Sure thing friend!
 
I was clicked yo!
Button
 
Cool, I’ll do
something neat
 
I was clicked yo!
 
Cool, I’ll do
something neat
 
Hey, so I don’t
care about your
clicks anymore, k?
 
No prob friend!
 
Observer Design Pattern
 
How is event based programming usually implemented?
 
Observer Design Pattern
 
Observer Design Pattern
: A software design pattern in which an object,
called the subject, maintains a list of its dependents, called observers,
and notifies them automatically of any state changes, usually by calling
on of their methods.
 
Observer Design Pattern -
Example
Observable (e.g.,
jcrew.com)
 
Contains several state
changes of interest:
 
Sale Begins
 
New Store Opening
 
New Product Available
 
Floryan
Sherriff
Brunelle
 
OBSERVERS
 
Observer Design Pattern -
Example
Observable (e.g.,
jcrew.com)
 
Contains several state
changes of interest:
 
Sale Begins
FLORYAN
 
New Store Opening
 
New Product Available
FLORYAN
Floryan
Sherriff
Brunelle
 
I want to know when sales
begin and when new
products come out
 
Observer Design Pattern -
Example
Observable (e.g.,
jcrew.com)
 
Contains several state
changes of interest:
 
Sale Begins
FLORYAN
 
New Store Opening
Sherriff
 
New Product Available
FLORYAN
SHERRIFF
Floryan
Sherriff
Brunelle
 
I care about when new stores
open and new products
available
 
Observer Design Pattern -
Example
Observable (e.g.,
jcrew.com)
 
Contains several state
changes of interest:
 
Sale Begins
FLORYAN
 
New Store Opening
Sherriff
 
New Product Available
FLORYAN
SHERRIFF
Floryan
Sherriff
Brunelle
 
You guys are lame, I don’t
care about any of that stuff.
 
Observer Design Pattern -
Example
Observable (e.g.,
jcrew.com)
 
***A NEW PRODUCT IS
AVAILABLE (PANTS)
 
Sale Begins
FLORYAN
 
New Store Opening
Sherriff
 
New Product Available
FLORYAN
SHERRIFF
Floryan
Sherriff
Brunelle
 
Observer Design Pattern -
Example
Observable (e.g.,
jcrew.com)
 
A NEW PRODUCT IS
AVAILABLE (PANTS)
 
Sale Begins
FLORYAN
 
New Store Opening
Sherriff
 
New Product Available
FLORYAN
SHERRIFF
Floryan
Sherriff
Brunelle
 
Yo! Some new
pants are
available
 
Yo! Some new
pants are
available
 
Observer Design Pattern
 
Ok, a little more detail now
 
Observer Design Pattern 
 UML Diagram
Observable
--------------------
Map<String, List<Observer>>
attach(String, Observer)
detach(String, Observer)
 
 
So far we have:
 
-
An 
observable
 holds a map of string event
types to the list of observable objects that
care about that event.
 
-
An 
observer
 can be 
attached
 (register) for an
event type (or multiple types.
 
-
An 
observer
 can be 
removed
 from a list (no
longer cares about getting those notifications.
 
-
One 
observer
 can register for 
many different
events
 on many observables, and visa versa.
Observable
--------------------
Map<String, List<Observer>>
attach(String, Observer)
detach(String, Observer)
 
 
Observer Design Pattern 
 UML Diagram
Interface Observer
--------------------
handleEvent(Event e)
 
Concrete Observer (e.g., Floryan)
--------------------
handleEvent(Event e)
 
 
e.g., attach(“SaleBegins”, this);
“this” is the observer here (Floryan)
Observable
--------------------
Map<String, List<Observer>>
attach(String, Observer)
detach(String, Observer)
notify(Event e)
 
Observer Design Pattern 
 UML Diagram
Interface Observer
--------------------
handleEvent(Event e)
 
Concrete Observer (e.g., Floryan)
--------------------
handleEvent(Event e)
 
 
Event Occurred 
 Call handleEvent
on any observer that is registered
 
Observer Design Pattern 
 UML Diagram
Observable
--------------------
Map<String, List<Observer>>
attach(String, Observer)
detach(String, Observer)
notify(Event e)
 
Interface Observer
--------------------
handleEvent(Event e)
 
Concrete Observer (e.g., Floryan)
--------------------
handleEvent(Event e)
 
Event
--------------------
Observable source
String eventType
 
 
ConcreteEvent (e.g., SaleBeginsEvent)
--------------------
//Extra data associated w/ event
Data SaleDate
Location
Etc
 
 
 
-
Event contains the 
source
 (which thing fired
this event) and the 
eventType
 (in case we
are interested in more than one and need
to distinguish).
 
-
ConcreteEvent
 adds 
extra data 
the
observer might be interested in regarding
the event that just occurred and is passed
into the handleEvent() method
 
Observer Design Pattern 
 UML Diagram
Observable
--------------------
Map<String, List<Observer>>
attach(String, Observer)
detach(String, Observer)
notify(Event e)
 
Interface Observer
--------------------
handleEvent(Event e)
 
Concrete Observer (e.g., Floryan)
--------------------
handleEvent(Event e)
 
Event
--------------------
Observable source
String eventType
 
 
ConcreteEvent (e.g., SaleBeginsEvent
--------------------
//Extra data associated w/ event
Data SaleDate
Location
Etc
 
 
Button (e.g.,)
--------------------
 
 
 
Attaches, detaches
 
Notifies 
 Passes Event
 
Parameter to Notify()
 
Reacts to event in
meaningful way
 
Sequence Diagram
 
 
 
Demo
 
//e.g., Player object extends Subject that contains health, ammo, etc.
public interface 
Subject {
     
public void 
registerObserver(Observer observer);
     
public void 
removeObserver(Observer observer);
     
public void 
notifyObservers();
}
 
S
u
b
j
e
c
t
.
j
a
v
a
 
Simple Example
 
import
 java.util.ArrayList;
public class 
Player 
implements
 Subject{
 
 
private
 ArrayList<Observer> observers = 
new
 ArrayList<Observer>();
 
public
 
void
 registerObserver(Observer observer) {
  
 observers.add(observer);
 
}
 
public void 
removeObserver(Observer observer) {
  
 observers.remove(observer);
 
}
 
P
r
o
d
u
c
t
.
j
a
v
a
 
Simple Example
 
private
 int health;
private 
int ammo;
String id;
public Player(int health, int ammo,String id) {
  
super
();
  
this.health 
= health;
  
this.ammo
= ammo;
  
this.id = id
;
 
}
 
Continue…
 
Simple Example
 
 
public void reduceHealth(int amount) {
  
this.health 
= this.health - amount;
  
notifyObservers(new HealthChangeEvent(this));
 
}
 
public void notifyObservers(Event e) {
f
o
r
 
(
O
b
s
e
r
v
e
r
 
o
b
 
:
 
o
b
s
e
r
v
e
r
s
)
 
{
 
 
 
 
 
 
 
 
 
 
 
 
 
o
b
.
u
p
d
a
t
e
(
e
)
;
     
 
 }
}
}
 
Continue…
 
Simple Example
 
public interface 
Observer{
 
  
public void 
update(Event e);
}
 
O
b
s
e
r
v
e
r
.
j
a
v
a
 
public class 
HealthBar implements Observer{
 
 
GUIElement theBar;
 
 
public void 
update(Event e) {
  
//health is now e.getSubject().getHealth();
  
theBar.showHealth(e.getSubject().getHealth());
 
}
}
 
H
e
a
l
t
h
B
a
r
.
j
a
v
a
 
Simple Example
 
public class 
ObserverPatternMain {
 
public static void 
main(String[] args) {
       
  
 Player p = new Player();
 
  
HealthBar b = new HealthBar();
 
  
p.registerObserver(b);
    }
 
O
b
s
e
r
v
e
r
P
a
t
t
e
r
n
M
a
i
n
.
j
a
v
a
 
O
b
s
e
r
v
e
r
 
P
a
t
t
e
r
n
 
P
r
o
s
 
&
 
C
o
n
s
 
Pros:
Supports the principle to strive for loosely coupled designs between objects that interact.
Allows you to send data to many other objects in a very efficient manner.
No modification is needed to be done to the subject to add new observers.
You can add and remove observers at anytime.
 
Cons:
If not used carefully the observer pattern can add unnecessary complexity
The order of Observer notifications is undependable
Slide Note
Embed
Share

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Learn when and how to use the observer pattern, along with examples in games. Contrasting events vs. polling in software design patterns. Explore the structure of the observer pattern with practical examples.

  • Observer Pattern
  • Dependency Management
  • Software Design
  • Event-Driven Programming
  • Game Development

Uploaded on Sep 22, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Observer Design Pattern

  2. Observer Design Pattern Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

  3. When to use the observer pattern When you need many other objects to receive an update when another object changes Examples in Games: Notifying UI elements that game state has changed and thus health bar or other needs to be updated immediately Notifying a quest module that certain events have happened that lead towards quest completion

  4. Structure Of Observer

  5. Events vs. Polling

  6. Events vs. Polling Polling A software design pattern (using design pattern a bit loosely here) in which a process repeatedly checks another entity for a status change. Examples: - Keep pinging a server to make sure a connection stays alive - Every 10 ms, check the printer for readiness - In a game, check every frame whether the player incapacitated *Often used in low-level programming (more so than high level)

  7. Polling Example Were you clicked? Button Nah Button Were you clicked? Nah Main Application Button Were you clicked? Yep!!!!! Button

  8. Events vs. Polling Events A software design pattern in which a process waits patiently for an event of interest to occur and only reacts when necessary. Examples: - Server, tell me when you are ready to connect - Printer, let me know when you are ready to print - Game over screen waits to be notified that player is dead *Important: is NOT implemented using polling.

  9. Events Example Let me know when you get clicked, k? Button Sure thing friend! Cool, I ll do something neat I was clicked yo! Button Main Application Cool, I ll do something neat I was clicked yo! Button Hey, so I don t care about your clicks anymore, k? No prob friend!

  10. Observer Design Pattern How is event based programming usually implemented?

  11. Observer Design Pattern Observer Design Pattern: A software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling on of their methods.

  12. Observer Design Pattern - Example Observable (e.g., jcrew.com) Floryan Contains several state changes of interest: OBSERVERS Sale Begins Sherriff New Store Opening New Product Available Brunelle

  13. Observer Design Pattern - Example Observable (e.g., jcrew.com) I want to know when sales begin and when new products come out Floryan Contains several state changes of interest: Sale Begins FLORYAN Sherriff New Store Opening New Product Available FLORYAN Brunelle

  14. Observer Design Pattern - Example Observable (e.g., jcrew.com) Floryan Contains several state changes of interest: I care about when new stores open and new products available Sale Begins FLORYAN Sherriff New Store Opening Sherriff New Product Available FLORYAN SHERRIFF Brunelle

  15. Observer Design Pattern - Example Observable (e.g., jcrew.com) Floryan Contains several state changes of interest: Sale Begins FLORYAN Sherriff New Store Opening Sherriff New Product Available FLORYAN SHERRIFF Brunelle You guys are lame, I don t care about any of that stuff.

  16. Observer Design Pattern - Example Observable (e.g., jcrew.com) Floryan ***A NEW PRODUCT IS AVAILABLE (PANTS) Sale Begins FLORYAN Sherriff New Store Opening Sherriff New Product Available FLORYAN SHERRIFF Brunelle

  17. Observer Design Pattern - Example Observable (e.g., jcrew.com) Floryan Yo! Some new pants are available A NEW PRODUCT IS AVAILABLE (PANTS) Yo! Some new pants are available Sale Begins FLORYAN Sherriff New Store Opening Sherriff New Product Available FLORYAN SHERRIFF Brunelle

  18. Observer Design Pattern Ok, a little more detail now

  19. Observer Design Pattern UML Diagram So far we have: Observable -------------------- Map<String, List<Observer>> attach(String, Observer) detach(String, Observer) - An observable holds a map of string event types to the list of observable objects that care about that event. - An observer can be attached (register) for an event type (or multiple types. - An observer can be removed from a list (no longer cares about getting those notifications. - One observer can register for many different events on many observables, and visa versa.

  20. Observer Design Pattern UML Diagram Interface Observer -------------------- handleEvent(Event e) Observable -------------------- Map<String, List<Observer>> attach(String, Observer) detach(String, Observer) e.g., attach( SaleBegins , this); this is the observer here (Floryan) Concrete Observer (e.g., Floryan) -------------------- handleEvent(Event e)

  21. Observer Design Pattern UML Diagram Interface Observer -------------------- handleEvent(Event e) Observable -------------------- Map<String, List<Observer>> attach(String, Observer) detach(String, Observer) notify(Event e) Concrete Observer (e.g., Floryan) -------------------- handleEvent(Event e) Event Occurred Call handleEvent on any observer that is registered

  22. Observer Design Pattern UML Diagram Interface Observer -------------------- handleEvent(Event e) Observable -------------------- Map<String, List<Observer>> attach(String, Observer) detach(String, Observer) notify(Event e) Concrete Observer (e.g., Floryan) -------------------- handleEvent(Event e) Event -------------------- Observable source String eventType - Event contains the source (which thing fired this event) and the eventType (in case we are interested in more than one and need to distinguish). ConcreteEvent (e.g., SaleBeginsEvent) -------------------- //Extra data associated w/ event Data SaleDate Location Etc - ConcreteEvent adds extra data the observer might be interested in regarding the event that just occurred and is passed into the handleEvent() method

  23. Observer Design Pattern UML Diagram Interface Observer -------------------- handleEvent(Event e) Observable -------------------- Map<String, List<Observer>> attach(String, Observer) detach(String, Observer) notify(Event e) Attaches, detaches Notifies Passes Event Concrete Observer (e.g., Floryan) -------------------- handleEvent(Event e) Parameter to Notify() Button (e.g.,) -------------------- Reacts to event in meaningful way Event -------------------- Observable source String eventType ConcreteEvent (e.g., SaleBeginsEvent -------------------- //Extra data associated w/ event Data SaleDate Location Etc

  24. Sequence Diagram

  25. Demo Subject.java Subject.java //e.g., Player object extends Subject that contains health, ammo, etc. public interface Subject { public void registerObserver(Observer observer); public void removeObserver(Observer observer); public void notifyObservers(); }

  26. Simple Example Product.java Product.java import java.util.ArrayList; public class Player implements Subject{ private ArrayList<Observer> observers = new ArrayList<Observer>(); public void registerObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { observers.remove(observer); }

  27. Simple Example Continue private int health; private int ammo; String id; public Player(int health, int ammo,String id) { super(); this.health = health; this.ammo= ammo; this.id = id; }

  28. Simple Example Continue public void reduceHealth(int amount) { this.health = this.health - amount; notifyObservers(new HealthChangeEvent(this)); } public void notifyObservers(Event e) { for for (Observer (Observer ob ob : observers) { : observers) { ob.update ob.update(e); } } } (e);

  29. Simple Example Observer.java Observer.java public interface Observer{ public void update(Event e); } HealthBar.java HealthBar.java public class HealthBar implements Observer{ GUIElement theBar; public void update(Event e) { //health is now e.getSubject().getHealth(); theBar.showHealth(e.getSubject().getHealth()); } }

  30. Simple Example ObserverPatternMain.java ObserverPatternMain.java public class ObserverPatternMain { public static void main(String[] args) { Player p = new Player(); HealthBar b = new HealthBar(); p.registerObserver(b); }

  31. Observer Pattern Pros & Observer Pattern Pros & Cons Cons Pros: Supports the principle to strive for loosely coupled designs between objects that interact. Allows you to send data to many other objects in a very efficient manner. No modification is needed to be done to the subject to add new observers. You can add and remove observers at anytime. Cons: If not used carefully the observer pattern can add unnecessary complexity The order of Observer notifications is undependable

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#