← Back to scenarios
ScenarioCatalog DB

Chat room mediator

Route user messages through a chat-room mediator instead of direct user-to-user communication.

Problem

A chat application must coordinate message delivery among users without requiring each user to know or directly depend on every other participant.

Related patterns

Implementations

Mediator

TypeScriptApplication

Mediator in TypeScript

Coordinates form fields through a mediator so individual controls do not need direct knowledge of one another.

TypeScript
interface FormMediator {
  notify(sender: FormField, event: "changed"): void;
}

abstract class FormField {
  constructor(protected readonly mediator: FormMediator) {}

  abstract changed(): void;
}

class CountryField extends FormField {
  private value = "";

  setValue(value: string) {
    this.value = value;
    this.changed();
  }

  changed() {
    this.mediator.notify(this, "changed");
  }

  getValue() {
    return this.value;
  }
}

class StateField extends FormField {
  private enabled = false;

  setEnabled(enabled: boolean) {
    this.enabled = enabled;
    console.log(`State field enabled: ${enabled}`);
  }

  changed() {
    this.mediator.notify(this, "changed");
  }
}

class CheckoutFormMediator implements FormMediator {
  country!: CountryField;
  state!: StateField;

  notify(sender: FormField, event: "changed") {
    if (sender === this.country && event === "changed") {
      this.state.setEnabled(this.country.getValue() === "US");
    }
  }
}

const mediator = new CheckoutFormMediator();
mediator.country = new CountryField(mediator);
mediator.state = new StateField(mediator);

mediator.country.setValue("US");
mediator.country.setValue("DE");

Associated technologies