Observer Pattern - CoffeeScript Design Patterns

By on

Here’s the classical version of the Observer pattern outlined in the GoF book. This implementation uses the List class and Iterator pattern to add and iterate observers. For those more familiar with the pub/sub terminology the Observer is the Subscriber and the Subject is the Publisher.

# * Knows its obvservers. Any number of Observer objects
#   may observe a subject
# * Provides an interface for attaching and detaching # Observer objects.

class Subject
  constructor: ()->
    @counter = 0
    @observers = new List()

  attach: (o)->
    o._POINTER_ = @counter
    @observers.append o
    @counter += 1

  detach: (o)->
    @observers.remove o

  notify: ()->
    i = new ConcreteIterator @observers
    while not i.isDone()
      i.currentItem().update @
    i.next()

# * Defines an updating interface for objects that should
#   be notified of changes in a subject
# * Sends a notification to its observers when its
#   state changes.

class Observer
  update: (theChangedSubject)->

# Stores state of interest to ConcreteObserver objects

class ConcreteSubject extends Subject

# * Maintains a reference to a ConcreteSubject object
# * Stores state that should stay consistent with
#   the subject's
# * Implements the Observer updating interface to keep
#   its state consistent with the subject's

class ConcreteObserver extends Observer
  update: (theChangedSubject)->
    console.log "Updated"

Usage:

subject = new ConcreteSubject()
observer = new ConcreteObserver()
subject.attach observer

# Later on...

subject.notify()


Update: Fixed old links and formatting