功能:
统计一组用户的银两和金币.
一.用户接口和实现
interface UserInterface
{
public function accept(Visitor $visitor);
}
class User implements UserInterface
{
private $uid;
private $silver;
private $money;
public function __construct($uid, $silver, $money)
{
$this->uid = $uid;
$this->silver = $silver;
$this->money = $money;
}
/**
* @return mixed
*/
public function getUid()
{
return $this->uid;
}
/**
* @return mixed
*/
public function getSilver()
{
return $this->silver;
}
/**
* @return mixed
*/
public function getMoney()
{
return $this->money;
}
public function accept(Visitor $visitor)
{
$visitor->visitUser($this);
}
}
二.访问者接口和实现
interface VisitorInterface
{
public function visitUser(User $user);
}
class Visitor implements VisitorInterface
{
public $silverTotal = 0;
public $moneyLevel = 0;
public function visitUser(User $user)
{
$this->silverTotal += $user->getSilver();
$this->moneyLevel += $user->getMoney();
}
public function __toString()
{
return "总计下属用户:银两合计:{$this->silverTotal};金币合计:{$this->moneyLevel}";
}
}
三.调用:
// 模拟数据库读取一批用户
$user = new User(1, 10, 200);
$list = [];
$list[] = clone $user;
$list[] = clone $user;
$list[] = clone $user;
$list[] = clone $user;
$list[] = clone $user;
$visitor = new Visitor();
foreach ($list as $user) {
$user->accept($visitor);
}
echo $visitor;