I'm learning and try to practice design patterns, I was trying to implement the mediator pattern based on this explanation, The code works as I wanted to do it, but as I changed a few things and implemented methods and classes inside the concrete class, I don't know if the pattern is correctly implemented, can you please comment on this.
<?php
namespace DesignPatternsPractice\Mediator;
interface Mediator
{
public function notify(object $sender, string $event);
}
class ConcreteMediator implements Mediator {
private $component;
public function __construct($component) {
$this->component = $component;
$this->component->setMediator($this);
$this->family = new Family();
$this->family->setMediator($this);
}
public function notify($sender, $event) {
if($sender instanceof Kidnapper && $event === "called_family") {
echo "The family suspected a kidnapping, didn't responded the call and called a mediator \n";
$this->family->callMediator();
} else if($sender instanceof Kidnapper && $event === "called_mediator") {
$this->callFamily();
}
if ($sender instanceof Family && $event === "called_mediator") {
echo "Mediator is ready to respond the new call from the kidnapper\n";
}
if($sender instanceof ConcreteMediator && $event === "called_police") {
echo "The police does not negotiates with kidnappers and the victim was rescued \n";
}
}
public function callFamily() {
echo "The family responded no to the demands and tell the mediator to call the police \n";
$this->callPolice();
}
public function callPolice() {
$this->notify($this, "called_police");
}
}
class BaseComponent {
protected $mediator;
public function __construct(Mediator $mediator = null)
{
$this->mediator = $mediator;
}
public function setMediator(Mediator $mediator): void
{
$this->mediator = $mediator;
}
}
class Kidnapper extends BaseComponent {
public function callFamily() {
$this->mediator->notify($this, "called_family");
}
public function callMediator() {
echo "Mediator asked for demands\n";
$this->mediator->notify($this, "called_mediator");
}
}
class Family extends BaseComponent {
public function callMediator() {
$this->mediator->notify($this, "called_mediator");
}
}
$kn = new Kidnapper();
$mediator = new ConcreteMediator($kn);
$kn->callFamily();
$kn->callMediator();
Aucun commentaire:
Enregistrer un commentaire