PHP Design Pattern Viewer pattern (Observer) Detail and code example _php tutorial

Source: Internet
Author: User
Tags php example
"Intent"

Defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated "GOF95", also known as publish-subscribe (publish-subscribe) mode, model-view (model-view) mode, Source-Listen (Source-listener) mode, or dependent (dependents) mode

"Observer pattern structure diagram"


"Main role in observer mode"

1. Abstract theme (Subject) role: The subject role saves all references to the Observer object in a collection, each subject can have any number of observers. Abstract topics provide an interface for adding and removing observer objects.
2. Abstract observer (OBSERVER) Role: Define an interface for all specific observers to update themselves when the subject of the observation changes.
3. Specific theme (ConcreteSubject) role: stores the relevant state to the specific observer object, and notifies all registered observers when the internal state of the specific subject changes. A specific theme role is typically implemented with a specific subclass.
4. The specific observer (Concretedobserver) Role: stores a specific Subject object, stores the related state, implements the update interface required by the abstract observer role, so that its state and the state of the subject remain consistent.

"The pros and cons of the Observer pattern"

The advantages of the Observer pattern:

1. The coupling between the viewer and the subject is small;
2. Support for broadcast communications;

Disadvantages of the Observer pattern:

Because observers do not know the existence of other observers, it may be ignorant of the ultimate cost of changing the target. This may cause an unexpected update.


"Observer pattern for scenarios"

When an abstract model has two facets, one aspect depends on the other.
When a change to an object needs to change other objects at the same time, it is not known how many objects to change.
When an object must notify other objects, it cannot assume that other objects are who. In other words, you don't want these objects to be tightly coupled.

"Observer mode and other modes"

1. Mediator mode (mediator): By encapsulating Complex update semantics, Changemanager acts as a mediator between the target and the observer.
2. Singleton mode (singleton mode): Changemanager can use singleton mode to ensure that it is unique and can be accessed globally.


"Observer mode PHP Example"

Copy the Code code as follows:

/**
* Viewer Mode
* @package Design pattern
*/

/**
* Abstract Theme Characters
*/
Interface Subject {

/**
* Add a new Observer object
* @param Observer $observer
*/
Public function Attach (Observer $observer);

/**
* Delete a registered Observer object
* @param Observer $observer
*/
Public Function Detach (Observer $observer);

/**
* Notify all registered Observer objects
*/
Public function notifyobservers ();
}

/**
* Specific Theme Roles
*/
Class ConcreteSubject implements Subject {

Private $_observers;

Public Function __construct () {
$this->_observers = Array ();
}

/**
* Add a new Observer object
* @param Observer $observer
*/
Public function Attach (Observer $observer) {
Return Array_push ($this->_observers, $observer);
}

/**
* Delete a registered Observer object
* @param Observer $observer
*/
Public Function Detach (Observer $observer) {
$index = Array_search ($observer, $this->_observers);
if ($index = = = FALSE | |! array_key_exists ($index, $this->_observers)) {
return FALSE;
}

unset ($this->_observers[$index]);
return TRUE;
}

/**
* Notify all registered Observer objects
*/
Public Function notifyobservers () {
if (!is_array ($this->_observers)) {
return FALSE;
}

foreach ($this->_observers as $observer) {
$observer->update ();
}

return TRUE;
}

}

/**
* Abstract Observer role
*/
Interface Observer {

/**
* Update method
*/
Public function update ();
}

Class Concreteobserver implements Observer {

/**
* The name of the viewer
* @var
*/
Private $_name;

Public function __construct ($name) {
$this->_name = $name;
}

/**
* Update method
*/
Public Function Update () {
Echo ' Observer ', $this->_name, ' has notified.
';
}

}
Instantiate class:
$subject = new ConcreteSubject ();

/* ADD first Observer */
$observer 1 = new Concreteobserver (' Martin ');
$subject->attach ($observer 1);

Echo '
The first notify:
';
$subject->notifyobservers ();

/* Add a second observer */
$observer 2 = new Concreteobserver (' Phppan ');
$subject->attach ($observer 2);

Echo '
The Second notify:
';
$subject->notifyobservers ();

/* Delete the first observer */
$subject->detach ($observer 1);

Echo '
The third notify:
';
$subject->notifyobservers ();
Specific cases:

/**
* 3.1php design mode-Observer mode
* 3.1.1 Concept: In fact the Observer pattern this is a more easily understood pattern, it is an event system, meaning
* This pattern allows a class to observe the state of another class, and when the observed class state changes,
* Observation classes can receive notifications and act accordingly; Observer mode provides you with the ability to avoid component
* Another method of tight coupling
* 3.1.2 Key points:
* 1. Additional observer, Observer,;-> an observer;-> to notify the observer when the condition is met;-> observation conditions
* 2. Observer---acceptance method
* 3.1.3 Disadvantages:
* 3.1.4 Observer pattern in PHP applications: There are many aspects of observer application in Web development
* Typical: User registration (verification email, user information activation), e-mail/SMS notification when shopping site is under order
* 3.1.5php Internal support
* Splsubject interface, which represents the object being observed,
* Its structure:
* Interface Splsubject
* {
* Public Function Attach (Splobserver $observer);
* Public Function Detach (Splobserver $observer);
* Public function notify ();
* }
* Splobserver interface, which represents an object that acts as an observer,
* Its structure:
* Interface Splobserver
* {
* Public Function Update (Splsubject $subject);
* }
*/

/**
* User Login-Annotation Viewer mode
*/
Class User implements Splsubject {
Registered Observer
Public $observers = Array ();

Action type
CONST Observer_type_register = 1;//Registration
CONST Observer_type_edit = 2;//Edit

/**
* Additional observers
* @param SPLOBSERVER $observer Observer
* @param int $type observation type
*/
Public function Attach (Splobserver $observer, $type)
{
$this->observers[$type] [] = $observer;
}

/**
* Remove Viewer
* @param SPLOBSERVER $observer Observer
* @param int $type observation type
*/
Public Function Detach (Splobserver $observer, $type)
{
if ($idx = Array_search ($observer, $this->observers[$type], true))
{
unset ($this->observers[$type [$idx]);
}
}

/**
* Notify observers when conditions are met
* @param int $type observation type
*/
Public function Notify ($type)
{
if (!empty ($this->observers[$type]))
{
foreach ($this->observers[$type] as $observer)
{
$observer->update ($this);
}
}
}

/**
* Add user
* @param str $username user name
* @param str $password password
* @param str $email mailbox
* @return BOOL
*/
Public Function AddUser ()
{

Execute SQL

Database Insert Succeeded
$res = true;

Invoke Notification Viewer
$this->notify (Self::observer_type_register);

return $res;
}

/**
* User Information editing
* @param str $username user name
* @param str $password password
* @param str $email mailbox
* @return BOOL
*/
Public Function Edituser ()
{

Execute SQL

Database Update succeeded
$res = true;

Invoke Notification Viewer
$this->notify (Self::observer_type_edit);

return $res;
}
}

/**
* Viewer-Send mail
*/
Class Send_mail implements Splobserver
{
/**
* Change information of the corresponding observed person
* @param splsubject $subject
*/
Public Function Update (Splsubject $subject)
{
$this->sendmail ($subject->email, $title, $content);
}

/**
* Send mail
* @param str $email email address
* @param str $title message header
* @param str $content mail content
*/
Public Function SendEmail ($email, $title, $content)
{
Call Mail interface, send mail
}
}
?>

http://www.bkjia.com/PHPjc/750852.html www.bkjia.com true http://www.bkjia.com/PHPjc/750852.html techarticle "Intent" defines a one-to-many dependency between objects, and when the state of an object changes, all objects that depend on it are notified and automatically updated "GOF95" also known as ...

  • Related Article

    Contact Us

    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

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.