Copy CodeThe code is as follows:
<?php
/**
* Observer mode
*
* Defines a one-to-many dependency between objects so that when an object's state changes, all objects that depend on it are notified and automatically refreshed
* The ability to easily create objects that view the state of the target object, and to provide the specified functionality that is not coupled to the core object
* Plug-in System
*/
Class Observerable
{
Private $_observers = Array ();
Public Function Registerobserver ($observer)
{
$this->_observers[] = $observer;
}
Public Function Removeobserver ($observer)
{
$key = Array_search ($observer, $this->_observers);
if (!) ( $key = = False))
{
unset ($this->_observers[$key]);
}
}
Public Function Notifyobservers ()
{
foreach ($this->_observers as $observer)
{
if ($observer instanceof observer) $observer->update ($this);
}
}
}
Interface Observer
{
Public Function Update ($observer);
}
Interface Displayelement
{
Public function display ();
}
--Instance class definition
Class Newsobserverable extends Observerable
{
Private $_sports_news;
Public Function setsportsnews ($data)
{
$this->_sports_news = $data;
$this->notifyobservers ();
}
Public Function Getsportsnews ()
{
return $this->_sports_news;
}
Private $_local_news;
Public Function setlocalnews ($data)
{
$this->_local_news = $data;
$this->notifyobservers ();
}
Public Function Getlocalnews ()
{
return $this->_local_news;
}
}
Class Sportsnews implements Observer,displayelement
{
Private $_data = null;
Public Function Update ($observer)
{
if ($this->_data!= $observer->getsportsnews ())
{
$this->_data = $observer->getsportsnews ();
$this->display ();
}
}
Public Function display ()
{
echo $this->_data.date ("y-m-d h:i:s"). " <br/> ";
}
}
Class LocalNews implements Observer,displayelement
{
Private $_data = null;
Public Function Update ($observer)
{
if ($this->_data!= $observer->getlocalnews ())
{
$this->_data = $observer->getlocalnews ();
$this->display ();
}
}
Public Function display ()
{
echo $this->_data.date ("y-m-d h:i:s"). " <br/> ";
}
}
--Materialized---
$objObserver = new Newsobserverable ();
$local = new LocalNews ();
$sports = new Sportsnews ();
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service