THN Interview Prep

Mediator (Behavioral)

Intent / problem it solves

Define an object that encapsulates how colleagues interact, promoting loose coupling so components talk through the mediator instead of many-to-many wiring.

When to use / when NOT

Use for chat rooms, air-traffic-style coordination, complex UI forms, or orchestrating microflows.

Avoid when direct calls are clear or the mediator risks becoming a god service.

Structure

Mediator interface with notify(sender, event); colleagues hold mediator reference and route messages centrally.

Loading diagram…

Go example

package main

import "fmt"

type Dialog interface {
	Notify(source string, payload string)
}

type Form struct {
	mediator Dialog
}

func (form *Form) Change(field string, value string) {
	if form.mediator != nil {
		form.mediator.Notify(field, value)
	}
}

type LoginDialog struct {
	submitEnabled bool
}

func (dialog *LoginDialog) Notify(source string, payload string) {
	if source == "password" && len(payload) >= 8 {
		dialog.submitEnabled = true
	}
	fmt.Println("submitEnabled", dialog.submitEnabled)
}

func main() {
	dialog := &LoginDialog{}
	form := Form{mediator: dialog}
	form.Change("password", "password123")
}

JavaScript example

class DialogMediator {
  constructor() {
    this.zipVisible = false;
  }

  notify(sourceName, value) {
    if (sourceName === 'country' && value === 'US') {
      this.zipVisible = true;
    }
  }
}

class Field {
  constructor(name, mediator) {
    this.name = name;
    this.mediator = mediator;
  }

  change(value) {
    this.mediator.notify(this.name, value);
  }
}

const mediator = new DialogMediator();
const countryField = new Field('country', mediator);
countryField.change('US');
console.log(mediator.zipVisible);

Interview phrase

“Mediator centralizes cross-widget rules so individual fields do not know about each other—only the dialog policy does.”

Map to LLD for form wizards, chat rooms, or airport gate coordination in LLD case studies.

Last updated on

Spotted something unclear or wrong on this page?

On this page