• Category: behavioral
  • Type: object
  • Motivation: mediator(third part object), as the provide to control between two objects (called colleagues)

diagram

do {
    let atc = ATC()
    let flight = Flight(atc)
    let runway = Runway(atc)

    atc.register(flight)
    atc.register(runway)

    runway.land()
    flight.land()
    /*
      Output:
      Landing permission granted.
      Sucessfully landed
    */
}
protocol Mediator
{
	var isLanding: Bool { get set}

	// just demostrate to add command to mediator, in this example it do
	// nothing
	func register(_ command: Command)
}

class ATC: Mediator
{
	var isLanding: Bool = false

	var commands: [Command] = []

	func register(_ command: Command)
	{
		commands.append(command)
	}
}

protocol Command
{
	init(_ atc: Mediator)
	func land()
}

class Flight: Command
{
	private var atc: Mediator
	required init(_ atc: Mediator)
	{
		self.atc = atc
	}

	func land()
	{
		if atc.isLanding {
			print("Sucessfully landed")
			atc.isLanding = true
		} else {
			print("Waiting for landing")
		}
	}
}

class Runway: Command
{
	private var atc: Mediator
	required init(_ atc: Mediator)
	{
		self.atc = atc
	}

	func land()
	{
		atc.isLanding = true
		print("Landing permission granted.")
	}
}