<?php
/**
**observer model :實現一對多的設計,一個對象改變時,依賴於該對象的,都得到通知並且改變。
**可以在獨立的對象中維護一個對象,專用於解除主體與依賴者的直接關係
**又稱爲 發佈-監聽模式,從屬模式,源-監聽模式,模式-視圖模式
**觀察者模式應用:用戶註冊(驗證郵件,用戶信息激活)
**
***********/
interface SqlSubject{
function attach(SqlObserver $observer);
function detach(SqlObserver $observer);
function notify();
}
interface SqlObserver{
function update(SqlSubject $subject);
}
class Subject implements SqlSubject{
private $_object = array();
public function attach(SqlObserver $object){
if(!in_array($object,$this->_object)){
$_object[] = $object;
}
}
public function detach(SqlObserver $observer){
if(false != ($index=array_search($observer,$this->_object))){
unset($this->_object[$index]);
}
}
public function post(){
$this->notify();
}
public function notify(){
foreach($this->_object as $val){
$val->update($this);
}
}
public function setCount($count){
echo $count;
}
public function setIntegeral($integeral){
echo $integeral;
}
}
class Observer1 implements SqlObserver{
public function update(SqlSubject $subject){
$subject->setIntegeral(10);
}
}
class Observer2 implements SqlObserver{
public function update(SqlSubject $subject){
$subject->setCount(20);
}
}
class Client{
public static function main(){
$subject = new Subject();
$subject->attach(new Observer1());
$subject->attach(new Observer2());
$subject->post();
}
}
Client::main();
?>
<?php
/**
**用戶註冊
*****/
interface SqlSubject{
function attach();
function detach();
function post();
}
interface SqlObject{
function update();
}
class UserSubject implements SqlSubject{
private $_userEmail = array();
function attach( SqlObject $email,$type){
if(!in_array($email,$type)){
$this->_userEmail[$type][] = $email;
}
}
function detach( SqlObject $email ,$type ){
if(FALSE ! = ($index = array_search($email,$_userEmail))){
unset($_userEmail[$type][$index]);
}
}
function post($type){
$this->notify($this);
}
function notify($type){
if(!empty($this->_userEmail[$type]))
foreach($this->_userEmail($type) as $observer){
$observer->update($this);
}
}
}
/**
**郵件觀察者模式
*********/
class EmailObject implements SqlObject{
function update(SqlSubject $subject){
$this->send($subject->email,$title,$content);
}
function send($email,$title,$content){
}
}