中介者模式/调停者模式(Mediator Pattern)

百度词条的解释

http://baike.baidu.com/view/3905086.htm

 
 
 
 
<?php
//中介者模式(调停者模式)
abstract class AbstractColleague {

	protected $number;

	public function getNumber() {
		return $this->number;
	}

	public function setNumber($number, AbstractMediator $am = null) {
		$this->number = $number;
	}

}

class ColleagueA extends AbstractColleague {

	public function setNumber($number, AbstractMediator $am = null) {
		if($am == null) {
			parent::setNumber($number);
			return;
		}
		$this->number = $number;
		$am->AaffectB();
	}

}

class ColleagueB extends AbstractColleague {

	public function setNumber($number, AbstractMediator $am = null) {
		if($am == null) {
			parent::setNumber($number);
			return;
		}
		$this->number = $number;
		$am->BaffectA();
	}

}

abstract class AbstractMediator {

	protected $a;

	protected $b;

	public function __construct(AbstractColleague $a, AbstractColleague $b) {
		$this->a = $a;
		$this->b = $b;
	}

	public abstract function AaffectB();

	public abstract function BaffectA();

}

class Mediator extends AbstractMediator {

	public function __construct(AbstractColleague $a, AbstractColleague $b) {
		parent::__construct($a, $b);
	}

	//处理A对B的影响
	public function AaffectB() {
		$this->b->setNumber($this->a->getNumber()*100);
	}

	//处理B对A的影响
	public function BaffectA() {
		$this->a->setNumber($this->b->getNumber()/100);
	}

}

$collA = new ColleagueA();
$collB = new ColleagueB();

$am = new Mediator($collA, $collB);

$collA->setNumber(1000, $am);
echo '通过设置A影响B<br/>collA的number值为:'.$collA->getNumber().'<br/>collB的unmber值为A的10倍:'.$collB->getNumber();
?>

你可能感兴趣的:(中介者模式/调停者模式(Mediator Pattern))