Created
August 4, 2018 14:38
-
-
Save bz0/73310373d800df29dbd946db557e8ae6 to your computer and use it in GitHub Desktop.
GoF Mediatorパターン
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User { | |
private $chatroom; | |
private $name; | |
public function __construct($name){ | |
$this->name = $name; | |
} | |
public function getName(){ | |
return $this->name; | |
} | |
public function setChatroom(Chatroom $value){ | |
$this->chatroom = $value; | |
} | |
public function getChatroom(){ | |
return $this->chatroom; | |
} | |
public function sendMessage($to, $message){ | |
$this->chatroom->sendMessage($this->name, $to, $message); | |
} | |
public function receiveMessage($from, $message){ | |
printf('<font color="#008800">%sさんから%sさんへ</font>:%s<hr>', $from, $this->getName(), $message); | |
} | |
} | |
class Chatroom{ | |
private $users = array(); | |
/* | |
* 部屋の入室 | |
* ユーザ単位にUserインスタンスをセット | |
*/ | |
public function login(User $user){ | |
$user->setChatroom($this); | |
if (!array_key_exists($user->getName(), $this->users)){ | |
$this->users[$user->getName()] = $user; | |
printf('<font color="#0000dd">%sさんが入室しました</font><hr>', $user->getName()); | |
} | |
} | |
public function sendMessage($from, $to, $message){ | |
//部屋に入室しているかチェック | |
if (array_key_exists($to, $this->users)){ | |
//誰に対してメッセージを渡すかを通知 | |
$this->users[$to]->receiveMessage($from, $message); | |
}else{ | |
printf('<font color="#dd0000">%sさんは入室していないようです</font><hr>', $to); | |
} | |
} | |
} | |
$chatroom = new Chatroom(); | |
$sasaki = new User('佐々木'); | |
$suzuki = new User('鈴木'); | |
$yoshida = new User('吉田'); | |
$kawamura = new User('川村'); | |
$chatroom->login($sasaki); | |
$chatroom->login($suzuki); | |
$chatroom->login($yoshida); | |
$chatroom->login($kawamura); | |
$sasaki->sendMessage('鈴木', '来週の予定は?'); | |
$suzuki->sendMessage('川村', '秘密です'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment