封装交互促进松散耦合明确的独立地这种模式定义了一个对象该对象封装了一组对象如何交互中介者使各对象不需要显式地相互引用从而使其耦合松散它允许你独立的改变他们的交互
ConcreteColleague(['kɔli:ɡ] 同事)2
Each colleague class knows its mediator object and communicates(沟通) with its mediator whenever it would have otherwise communicated with another colleague.
(每个同事类知道它的中介对象和与每当它本来与另一位同事沟通都通过与中介沟通来传达。)
ConcreteColleague(['kɔli:ɡ] 同事)1
Each colleague class knows its mediator object and communicates(沟通) with its mediator whenever it would have otherwise communicated with another colleague.
(每个同事类知道它的中介对象和与每当它本来与另一位同事沟通都通过与中介沟通来传达。)
ConcreteMediator(具体中介)
This class implements co-operative([kəu'ɔpərətiv] 合作) behaviour by co-ordinating([kəu'ɔ:dənit] 协调) Colleague objects. It also knows and maintains(维护) its colleagues.
(这个类实现合作行为通过协调同事对象。它还知道并维护自己的同事。)
Colleague(同事)
Each colleague class knows its mediator object and communicates(沟通) with its mediator whenever it would have otherwise communicated with another colleague.
(每个同事类知道它的中介对象和与每当它本来与另一位同事沟通都通过与中介沟通来传达。)
Mediator(中介)
This class defines an interface for communicating with Colleague objects.
(这个类定义了一个接口为了与同事对象沟通。)
<?php
class Colleague1 extends Colleague
{
public function notify($message) {
echo "Colleague1 Message is :" . $message . "";
}
}
class Colleague2 extends Colleague
{
public function notify($message) {
echo "Colleague2 Message is :" . $message . "";
}
}
class ConcreteMediator extends Mediator
{
private $_colleague1 = null;
private $_colleague2 = null;
public function send($message, $colleague) {
if ($colleague == $this->_colleague1) {
$this->_colleague1->notify($message);
} else {
$this->_colleague2->notify($message);
}
}
public function set($colleague1, $colleague2) {
$this->_colleague1 = $colleague1;
$this->_colleague2 = $colleague2;
}
}
abstract class Colleague {
private $_mediator = null;
public function Colleague($mediator) {
$this->_mediator = $mediator;
}
public function send($message) {
$this->_mediator->send($message, $this);
}
abstract public function notify($message);
}
abstract class Mediator {
abstract public function send($message, $colleague);
}
$objMediator = new ConcreteMediator();
$objC1 = new Colleague1($objMediator);
$objC2 = new Colleague2($objMediator);
$objMediator->set($objC1, $objC2);
$objC1->send("to c2 from c1");
$objC2->send("to c1 from c2");
评论