<?php
interface
ChatMediator {
public
function
sendMessage(
$msg
,
$user
);
public
function
addQQUser(
$user
);
}
abstract
class
User {
protected
$mediator
;
protected
$name
;
public
function
__construct(
$med
,
$name
){
$this
->mediator =
$med
;
$this
->name =
$name
;
}
public
abstract
function
send(
$msg
);
public
abstract
function
receive(
$msg
);
}
class
QQchat
implements
ChatMediator {
private
$users
;
public
function
__construct(){
$this
->users = null ;
}
public
function
addQQUser(
$user
){
$this
->users[] =
$user
;
}
public
function
sendMessage(
$msg
,
$user
) {
foreach
(
$this
->users
as
$k
=>
$v
){
if
(
$v
!=
$user
){
$v
->receive(
$msg
);
}
}
}
}
class
QQUser
extends
User {
public
function
send(
$msg
){
$this
->mediator->sendMessage(
$msg
,
$this
);
}
public
function
receive(
$msg
) {
echo
$this
->name.' receive '.
$msg
.'<br>' ;
}
}
$QQchat
=
new
QQchat();
$oMe
=
new
QQUser(
$QQchat
,
"张三"
);
$oFriend1
=
new
QQUser(
$QQchat
,
"李四"
);
$oFriend2
=
new
QQUser(
$QQchat
,
"王伟"
);
$oFriend3
=
new
QQUser(
$QQchat
,
"大哥"
);
$QQchat
->addQQUser(
$oMe
);
$QQchat
->addQQUser(
$oFriend1
);
$QQchat
->addQQUser(
$oFriend2
);
$QQchat
->addQQUser(
$oFriend3
);
$oMe
->send(
"Hi All"
);