Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Observer Pattern. Formal Definition Define a one-to-many dependency between objects so that when one object changes state, all its dependents are.

Similar presentations


Presentation on theme: "The Observer Pattern. Formal Definition Define a one-to-many dependency between objects so that when one object changes state, all its dependents are."— Presentation transcript:

1 The Observer Pattern

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

3 UML Diagram

4 Project Application This pattern is primarily used in our project to change the world when an event occurs. For example when a character moves it is the observer pattern that notifys all the hittable, and non-hittable objects in the world. This allows all screen objects to know the players position at all times and react accordingly.

5 Interfaces public interface Subject { public void addObserver( Observer o ); public void removeObserver( Observer o ); } public interface Observer { public void update( Subject o ); }

6 Code – Player Class public class Player implements Hittable, Runnable, Subject { private ArrayList observers = new ArrayList();.... public void moveRight(float amount) { x += amount; notifyObservers(); } public void moveLeft(float amount) { x -= amount; notifyObservers(); }

7 Code – Player Class public void addObserver( Observer o ) { observers.add( o ); } public void removeObserver( Observer o ) { observers.remove( o ); } private void notifyObservers() { // loop through and notify each observer Iterator i = observers.iterator(); while( i.hasNext() ) { Observer o = ( Observer ) i.next(); o.update( this ); }

8 Code – Hittable Class public class HSquare implements Hittable, Observer { private Player player;.... public HSquare(float x, float y, float w, float h) { player.addObserver(this); this.x = x; this.y = y; width = w; height = h; } public void update( Subject o ) { if( o == player ) { // Handling code goes here it is different for each object }

9 Changes needed to make this work? There really weren’t any changes besides adding the new methods.

10 Does this pattern help with code readability? This pattern helps manage which objects are connected to each other, however the code is no more readable than before.


Download ppt "The Observer Pattern. Formal Definition Define a one-to-many dependency between objects so that when one object changes state, all its dependents are."

Similar presentations


Ads by Google