Mediator Pattern - CoffeeScript Design Patterns

By on

I’ve made such good use of this pattern over the past year I’m surprised it wasn’t the first one in the CoffeeScript Design Patterns posts. The mediator pattern is great because it decouples all the various parts of an app from each other.

It’s great for admin screens, widget-style apps, with a little salt, and even for desert. What’s more is that you can use it in conjunction with the Observer pattern for even more extreme decoupling. That’s right folks. And you can have it now for one easy payment of $0.00.

# Abstract Colleague class  
# * Each Colleague class knows its Mediator object  
# * Each colleague communicates with its mediator whenever it  
#   would have otherwise communcicated with another colleague  
class Colleague  
  constructor: (@mediator) ->  
  changed: () ->  
    @mediator.colleagueChanged @

class ConcreteColleague1 extends Colleague  
  event: () ->  
    @changed()

class ConcreteColleague2 extends Colleague  
  event: () ->  
    @changed()

# Defines an interface for communicate with Colleague objects
class Mediator  
  colleagueChanged: (colleague) ->

# * Coordinating Collegue object behavior
# * Knows and maintains its colleagues
class ConcreteMediator extends Mediator  
  createColleagues: () ->
    @colleague1 = new ConcreteColleague1 @
    @colleague2 = new ConcreteColleague2 @
    @colleague1.event()
    @colleague2.event()

  colleagueChanged: (colleague) ->
    if colleague instanceof ConcreteColleague1
      console.log "colleague1 changed"
    else if colleague instanceof ConcreteColleague2
      console.log "colleague2 changed"

Usage:

m = new ConcreteMediator()  
m.createColleagues()