Zachary W. Huang

Home Projects Blog Guides Resume

Mediator

Idea: define how multiple objects interact through an intermediary - this keeps the objects from having explicitly know about each other, and it allows you to vary how these objects interact.

Below is an example of nontrivial interaction between multiple objects getting handled by a mediator.

class Mediator {
  colleagues: Colleague[] = [];

  addColleague(colleague: Colleague) {
    this.colleagues.push(colleague);
  }

  interact() {
    for (let colleague of this.colleagues) {
      colleague.interact();
    }
  }
}

abstract class Colleague {
  abstract interact(): void;
}

class ColleagueA extends Colleague {
  mediator: Mediator;
  state: string = "";

  constructor(mediator: Mediator) {
    super();
    this.mediator = mediator;
  }

  doThing() {
    this.mediator.interact();
    console.log(this.state);
  }

  interact() {
    this.state += "A"
  }
}

class ColleagueB extends Colleague {
  mediator: Mediator;
  state: string = "";

  constructor(mediator: Mediator) {
    super();
    this.mediator = mediator;
  }

  doThing() {
    this.mediator.interact();
    console.log(this.state);
  }

  interact() {
    this.state += "BB"
  }
}

function main() {
  const mediator = new Mediator();
  const a = new ColleagueA(mediator);
  mediator.addColleague(a);
  const b = new ColleagueB(mediator);
  mediator.addColleague(b);

  a.doThing(); // "A"
  b.doThing(); // "BBBB"
  a.doThing(); // "AAA"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024