CS3340:   Intro OOP and Design

 

Observer Pattern

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

Let objects propagate information without depending on each other much.

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

  • publish-subscribe / constraints / broadcast / change-update

Purpose:

Mainly used to implement distributed event handling systems.

oberserver diagram

 

 

3 Main Ideas:

Registration

  • Observer registers itself as a dependent of subject.

    subject addDependent: observer

Notification

  • Object notifies dependents when information changes by sending itself a "changed" message.

    changed: anArg
    {

      For each dependent { update: anArg }

    }

Update

  • Dependent can define what it does in response to changes by defining the update method


    update: anArg                                                            
    {                                                                                
          do whatever                                                         
    }                                                                               
© Lynne Grewe