php mode mediator (mediator pattern)

Almost, sleep, get another the next.

<?php
/*
The more classes we have in our software, the more complex their communication
becomes. The mediator pattern addresses this complexity by encapsulating it into
a mediator object. Objects no longer communicate directly, but rather through a
mediator object, therefore lowering the overall coupling.
*/

interface MediatorInterface {
	public function fight();
	public function talk();
	public function registerA(ColleagueA $a);
	public function registerB(ColleagueB $b);
}

class ConcreteMediator implements MediatorInterface {
	protected $talk;
	protected $fight;
	
	public function registerA(ColleagueA $a) {
		$this->talk = $a;
	}
	
	public function registerB(ColleagueB $b) {
		$this->fight = $b;
	}
	
	public function fight() {
		echo 'fighting...<br/>';
	}
	
	public function talk() {
		echo 'talking...<br/>';
	}
}

abstract class Colleague {
	protected $mediator;
	public abstract function doSomething();
}

class ColleagueA extends Colleague {
	public function __construct(MediatorInterface $mediator) {
		$this->mediator = $mediator;
		$this->mediator->registerA($this);
	}
	
	public function doSomething() {
		$this->mediator->talk();
	}
}

class ColleagueB extends Colleague {
	public function __construct(MediatorInterface $mediator) {
		$this->mediator = $mediator;
		$this->mediator->registerB($this);
	}
	
	public function doSomething() {
		$this->mediator->fight();
	}
}

$mediator = new ConcreteMediator();
$talkColleague = new ColleagueA($mediator);
$fightColleague = new ColleagueB($mediator);

$talkColleague->doSomething();
$fightColleague->doSomething();
?>

  Output:

talking...
fighting...

  

Guess you like

Origin www.cnblogs.com/aguncn/p/11184484.html