Design Patterns – Preventing a Mediator from Becoming a God Object

design-patterns

To keep classes decoupled I'm using the Mediator Pattern like so:

class Mediator {
  constructor(canvas, selectionBox, undoManager) {
    this.canvas = canvas
    this.selectionBox = selectionBox
    this.undoManager = undoManager
  }

  addText(text) {
    this.canvas.addText(text)
    this.undoManager.captureUndo()
    this.selectionBox.update()
  }

  addImage(image) {
    this.canvas.addImage(image)
    this.undoManager.captureUndo()
    this.selectionBox.update()
  }

  // ... etc
}

as more and more methods are added on the Mediator class, isn't it going to become a God Object?

If that's the case how do I resolve this? Perhaps create sub-mediators that group actions together and use a parent mediator to coordinate them?


(*) For the record I just started using this pattern and I'm not sure I'm doing this correctly.

Best Answer

The role of the Mediator Pattern is to encapsulate communication logic between objects, reducing dependencies between them (reducing coupling).

However, like with any encapsulation if you put everything into one bag you can end up with so called God Object.

Solution for this is to use Single Responsibility Principle and split mediator objects, creating groups around the same behaviour. Practical tip can be to use convention - noun + verbal noun (e.g. ImageResizer, ImageTextUpdater).

It is not an issue of mediator pattern itself but incorrect (too broad) encapsulation in one class.

Related Topic