9

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.

nicholaswmin
  • 2,019

2 Answers2

6

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.

1

No, your Mediator class does not look like it is becoming a God Object. A class is not a God Object because it has many methods, but because it can interact with nearly all other objects in your system. That is not the case for your Mediator class.

On a side node, the Mediator class looks more like the implementation of the Facade design pattern.
In a correct implementation of the Mediator pattern, the Mediator class would assist in updating the selectionBox when the canvas changes and vice versa. It would typically not be triggered by classes outside the Mediator pattern.