-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mediator.class.php
80 lines (70 loc) · 2.12 KB
/
Mediator.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
abstract class Colleague{
protected $mediator;
abstract public function sendMsg($who,$msg);
abstract public function receiveMsg($msg);
public function setMediator(Mediator $mediator){
$this->mediator = $mediator;
}
}
class ColleagueA extends Colleague
{
public function sendMsg($toWho,$msg)
{
echo "Send Msg From ColleagueA To: ".$toWho . '<br>';
$this->mediator->opreation($toWho,$msg);
}
public function receiveMsg($msg)
{
echo "ColleagueA Receive Msg: ".$msg . '<br>';
}
}
class ColleagueB extends Colleague
{
public function sendMsg($toWho,$msg)
{
echo "Send Msg From ColleagueB To: ".$toWho . '<br>';
$this->mediator->opreation($toWho,$msg);
}
public function receiveMsg($msg)
{
echo "ColleagueB Receive Msg: ".$msg . '<br>';
}
}
abstract class Mediator{
abstract public function opreation($id,$message);
abstract public function register($id,Colleague $colleague);
}
class MyMediator extends Mediator
{
protected static $colleagues;
function __construct()
{
if (!isset(self::$colleagues)) {
self::$colleagues = [];
}
}
public function opreation($id,$message)
{
if (!array_key_exists($id,self::$colleagues)) {
echo "colleague not found";
return;
}
$colleague = self::$colleagues[$id];
$colleague->receiveMsg($message);
}
public function register($id,Colleague $colleague)
{
if (!in_array($colleague, self::$colleagues)) {
self::$colleagues[$id] = $colleague;
}
$colleague->setMediator($this);
}
}
$colleagueA = new ColleagueA();
$colleagueB = new ColleagueB();
$mediator = new MyMediator();
$mediator->register(1,$colleagueA);
$mediator->register(2,$colleagueB);
$colleagueA->sendMsg(2,'hello admin');
$colleagueB->sendMsg(1,'shiyanlou');