Wzorzec mediator

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

interface Mediator {

    public function send(string $name, string $message): void;
}

class ConcreteMediator implements Mediator {

    private $colleagues = [];

    public function colleagueRegister(Colleague $colleague): void {
        $colleague->registerMediator($this);
        $this->colleagues[$colleague->getName()] = $colleague;
    }

    public function send(string $name, string $message): void {
        $this->colleagues[$name]->getMessage($message);
    }

}

class Colleague {

    private $mediator;
    private $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function registerMediator(Mediator $mediator): void {
        $this->mediator = $mediator;
    }

    public function getName() {
        return $this->name;
    }

    public function send(string $name, string $message): void {
        echo "Przesyłanie wiadomości od " . $this->name . " do " . $name . ": " . $message . '<br>';

        $this->mediator->send($name, $message); /// Rzeczywista komunikacja odbywa się za pośrednictwem mediatora!!!
    }

    public function getMessage(string $message): void {
        echo "Wiadomość odebrana przez " . $this->name . ": " . $message . '<br>';
    }

}

$michael = new Colleague("michael");
$john = new Colleague("john");
$lucy = new Colleague("lucy");


$mediator = new ConcreteMediator();
$mediator->colleagueRegister($michael);
$mediator->colleagueRegister($john);
$mediator->colleagueRegister($lucy);

$lucy->send('john', "Hello world.");

echo '<br>';

$michael->send('lucy', "Witaj!");
echo '<br>';

Komentarze wyłączone