<?php
namespace design\observer;
interface Observer{
public function modify($wear);
}
Wang 观察者
[PHP] 纯文本查看复制代码
<?php
namespace design\observer;
class Wang implements Observer
{
protected $wearing='';
public function modify($wear){
$this->wearing=$wear;
}
public function getWearing(){
return 'wang need wear '.$this->wearing;
}
}
Li观察着
[PHP] 纯文本查看复制代码
<?php
namespace design\observer;
class Li implements Observer
{
protected $wearing='';
public function modify($wear){
$this->wearing=$wear;
}
public function getWearing(){
return 'li need wear '.$this->wearing;
}
}
Song观察者
[PHP] 纯文本查看复制代码
<?php
namespace design\observer;
class Song implements Observer
{
protected $wearing='';
public function modify($wear){
$this->wearing=$wear;
}
public function getWearing(){
return 'song need wear '.$this->wearing;
}
}
二 . 被观察者相关代码
被观察者接口
[PHP] 纯文本查看复制代码
<?php
namespace design\observer;
interface Main{
public function register(Observer $observer);
public function notify($wear);
}
被观察者实现
[PHP] 纯文本查看复制代码
<?php
namespace design\observer;
class Weather implements Main
{
private $objects=[];
public function register(Observer $observer)
{
if(!in_array($observer,$this->objects)){
$this->objects []=$observer;
}
}
public function notify($wear)
{
foreach ($this->objects as $obj){
$obj->modify($wear);
}
}
}