PHP design Pattern: Behavioral Mode (ii)

Source: Internet
Author: User
< connect to an article >

4. Observer mode (OBSERVER):

Also called the Publish subscription pattern, when a principal object changes, the multiple observer objects that depend on it are notified and the response is automatically updated. Just like the newspaper, the news released today is only seen by the people who read the newspaper. If you publish another newspaper, it is the same.

Benefits: Broadcast communication, large range, Youboy, easy to operate a group, "public ownership."

Disadvantage: Cannot operate the individual in the group alone, can not implement on demand.

Scenario: Manipulate multiple objects and operate the same.

Code implementation:

[PHP] View plaincopy

<?php/** * Gifted Net Public Lesson sample code * * Viewer Mode Observer * * @author network full stack engineer teaching team * @see http://www.ucai.cn */function OU Tput ($string) {echo $string.  "\ n";      }//Order data Object Simple simulation, this is actually need to be observed object (Subject), but we will be independent, and//through the construction method into the Subject in our mode, so that the specific business more independent class order{//Order number        Private $id = ';        User ID Private $userId = ';        User name Private $userName = ';        Price private $price = ';        The next single time private $orderTime = ';              Order data is populated with a simple simulation, the actual application may read the user form input and handle the public function __set ($name, $value) {if (Isset ($this, $name)) {          $this $name = $value; }}//Get Order Properties Public Function __get ($name) {if (Isset ($this-$name)) {return $thi          S-> $name;      } return "";      }}//Hypothetical DB class, easy to test, will actually be stored in the real database class fakedb{public function Save ($data) {return true;         }} class Client {public static function test () {   Initializes an order data $order = New Order ();          $order->id = 1001;          $order->userid = 9527;          $order->username = "God";          $order->price = 20.0;            $order->ordertime = time ();          Save order to database $db = new Fakedb ();          $result = $db->save ($order); if ($result) {///The actual application may be written to the log file, where output ("[orderid:{$order->id}] [useid:{$order->us                Erid}] [price:{$order->price}] "); The actual application invokes the mail delivery service, such as sendmail, which outputs output directly ("Dear {$order->username}: Your order {$order->id} was confirmed                !" ); The actual application invokes the mail delivery service, such as sendmail, which outputs output directly ("Dear Manager:user {$order->username} (id:{$order->userid}) Sub            Mitted a New Order {$order->id}, please handle it asap! "); }}} client::test ();

<?php/** * Gifted Net Public Lesson sample code * * Viewer Mode Observer * * @author network full stack engineer teaching team * @see http://www.ucai.cn */function OU Tput ($string) {echo $string.  "\ n";      }//Order data Object Simple simulation, this is actually need to be observed object (Subject), but we will be independent, and//through the construction method into the Subject in our mode, so that the specific business more independent class order{//Order number        Private $id = ';        User ID Private $userId = ';        User name Private $userName = ';        Price private $price = ';        The next single time private $orderTime = ';              Order data is populated with a simple simulation, the actual application may read the user form input and handle the public function __set ($name, $value) {if (Isset ($this, $name)) {          $this $name = $value; }}//Get Order Properties Public Function __get ($name) {if (Isset ($this-$name)) {return $thi          S-> $name;      } return "";      }}//The Observer, responsible for maintaining the observer and in the event of a change, notifies the Observer class Ordersubject implements Splsubject {private $observers;        Private $order;         Public function __construct (Order $order) { $this->observers = new Splobjectstorage ();      $this->order = $order; }//Add an observer public function attach (Splobserver $observer) {$this->observers->attach ($observer)      ; }//Remove an observer public function detach (Splobserver $observer) {$this->observers->detach ($observer)      ; }//Notifies all observers public function notify () {foreach ($this->observers as $observer) {$obs          Erver->update ($this);      }}//returns the specific implementation of the Principal object for the observer to invoke public function GetOrder () {return $this->order;      }}//Record the Business data log (Actionlogobserver) and may actually have to abstract a layer to handle different actions (business operations), omitting the class Actionlogobserver implements splobserver{           Public Function Update (Splsubject $subject) {$order = $subject->getorder (); The actual application may be written to the log file, which outputs output directly ("[orderid:{$order->id}] [useid:{$order->userid}] [price:{$order->price}      ]" ); }//Send an order confirmation email to the user (UsermaiLobserver) class Usermailobserver implements splobserver{Public Function update (Splsubject $subject) {$o           Rder = $subject->getorder ();  The actual application invokes the mail delivery service, such as sendmail, which outputs output directly ("Dear {$order->username}: Your order {$order->id} was confirmed!"      ); }//Send Order Processing notification mail (Adminmailobserver) to the manager class Adminmailobserver implements splobserver{public Function update (           Splsubject $subject) {$order = $subject->getorder (); The actual application invokes the mail delivery service, such as sendmail, which outputs output directly ("Dear Manager:user {$order->username} (id:{$order->userid}) Submit      Ted a New Order {$order->id}, please handle it asap! ");      }}//Hypothetical DB class, easy to test, will actually be stored in the real database class fakedb{public function Save ($data) {return true;          }} class Client {public static function test () {//initialization of an order data $order = New Order ();          $order->id = 1001;          $order->userid = 9527; $order->useRname = "God";          $order->price = 20.0;            $order->ordertime = time ();          Binding Observer $subject = new Ordersubject ($order);          $actionLogObserver = new Actionlogobserver ();          $userMailObserver = new Usermailobserver ();          $adminMailObserver = new Adminmailobserver ();          $subject->attach ($actionLogObserver);          $subject->attach ($userMailObserver);          $subject->attach ($adminMailObserver);          Save order to database $db = new Fakedb ();          $result = $db->save ($order);          if ($result) {//Notifies the Observer $subject->notify (); }}} client::test ();

5. Intermediary mode (mediator):

Encapsulates a series of object interactions with a mediation object, so that the objects do not need to explicitly cross-reference each other. Similar to the Post office, the mailing and the recipient do not have to run very long distances, through the post office.

Benefits: simplifies the relationship between objects and reduces the generation of subclasses.

Cons: The intermediary object can become very complex and the system is difficult to maintain.

Scenario: No interaction is required for the display to be established.

Code implementation:

[PHP] View plaincopy

<?php/** * Gifted Net Public Lesson sample code * * Broker Mode Mediator * * @author network full stack engineer teaching team * @see http://www.ucai.cn */function Output ($string) {echo $string.  "\ n";   } abstract class Mediator {//Mediator role abstract public function send ($message, $colleague);       } abstract class Colleague {//abstraction object Private $_mediator = null;       Public function __construct ($mediator) {$this->_mediator = $mediator;       The Public function send ($message) {$this->_mediator->send ($message, $this);   } Abstract Public Function notify ($message);       } class Concretemediator extends Mediator {//specific mediator role private $_colleague1 = null;       Private $_colleague2 = null; Public function Send ($message, $colleague) {if ($colleague = = $this->_colleague1) {$this->_c           Olleague1->notify ($message);           } else {$this->_colleague2->notify ($message); }} public FunCtion Set ($colleague 1, $colleague 2) {$this->_colleague1 = $colleague 1;       $this->_colleague2 = $colleague 2; }} class Colleague1 extends colleague {//specific object role Public function notify ($message) {output (sprintf ('      Colleague-1:%s ', $message)); }} class Colleague2 extends colleague {//specific object role Public function notify ($message) {Output (sprintf (      ' Colleague-2:%s ', $message)); }} class Client {public static function test () {//Client $objMediator =           New Concretemediator ();           $objC 1 = new Colleague1 ($objMediator);           $objC 2 = new Colleague2 ($objMediator);           $objMediator->set ($objC 1, $objC 2);           $objC 1->send ("to C2 from C1");         $objC 2->send ("to C1 from C2"); }} client::test ();

6. Status mode (state):

objects behave differently in different states. Just like a girlfriend, happy to hold your hand, not happy to walk the dog. Different behaviors are shown in two states.

Benefits: Avoid the If statement utility, convenient to add new states, encapsulating the state transition rules.

Cons: Increase the number of system classes and objects.

Scenario: conversion for different functions of an object.

Code implementation:

[PHP] View plaincopy

<?php/** * Gifted Net Public Course Sample code * * State mode * * @author network full stack engineer teaching team * @see http://www.ucai.cn */function output ($string) {echo $string.  "\ n";  } abstract class Ilift {//Elevator four states const OPENING_STATE = 1;  Door open state Const CLOSING_STATE = 2;  Gate closed state Const RUNNING_STATE = 3; Operating state Const STOPPING_STATE = 4;            Stop state;//Set the state of the elevator public abstract function setState ($state);            First elevator door open action public abstract function open ();            The elevator door is open, and of course it has closed public abstract function close ();            Elevator to cadres, run up public abstract function run ();      The elevator is going to stop. Public abstract function Stop ();            }/** * Elevator implementation class */class Lift extends Ilift {private $state;        Public Function SetState ($state) {$this->state = $state; }//Elevator door close public Function close () {///elevator in what state to switch off ($this->state{Case Ilift::opening_state://If yes, you can close the door and modify the elevator status $this->setstate (ilift::closing_st                ATE);                Break                    Case Ilift::closing_state://If the elevator is closed, nothing is done//do;                return;                Break                    Case Ilift::running_state://If it is running, the door is closed, it also shows that do not do//do nothing;                return;                Break                    Case Ilift::stopping_state://If it is stopped, Ben is closed, nothing is done//do;                return;            Break          } output (' Lift colse ');                }//Elevator door open public Function open () {///elevator in what state to open switch ($this->state) {                    Case Ilift::opening_state://If the door is already open, nothing is done//do;                return;                Break Case Ilift::closing_state://If the lift is off, the $this can be turned on-> SetState (ilift::opening_state);                Break                    Case Ilift::running_state://Is running state, you can not open the door, do nothing//do anything;                return;                Break                Case Ilift::stopping_state://Stop State, indifferent to open the door $this->setstate (ilift::opening_state);            Break        } output (' Lift open '); }///The elevator starts to run public function run () {switch ($this->state) {case Ilift::opening_                    State://If you are already open in the door, then you can not run anything, nothing is done//do;                return;                Break                Case Ilift::closing_state://If the elevator is off, you can run $this->setstate (ilift::running_state);                Break                    Case Ilift::running_state://Is running state, then do nothing//do anything;                return;                Break Case Ilift::stopping_state://Stop State, can run $this->setstaTe (ilift::running_state);        } output (' Lift run '); }//Lift stop public Function stop () {switch ($this->state) {case ilift::opening                    _state://If already in the door open state, that must first stop, do not do anything//do nothing;                return;                Break                Case Ilift::closing_state://If the elevator is off, you can of course stop the $this->setstate (ilift::closing_state);                Break                Case Ilift::running_state://Running State, have run of course that also has stopped $this->setstate (ilift::closing_state);                Break                    Case Ilift::stopping_state://Stop State, do nothing//do anything;                return;            Break        } output (' Lift stop ');                            }} class Client {public static function test () {$lift = new lift (); The initial condition of the elevator should be the Stop state $lift->setstate (Ilift::stoPping_state);                            The first is the elevator door open, people go in $lift->open ();                            Then the elevator door closes $lift->close ();                   Then, the elevator runs up, up or down $lift->run ();          Finally arrived at the destination, the elevator survived $lift->stop (); }} client::test ();

<?php/** * Gifted Net Public Course Sample code * * State mode * * @author network full stack engineer teaching team * @see http://www.ucai.cn */function output ($string) {echo $string.  "\ n";  }/** * Defines an interface for an elevator. */abstract class liftstate{//Define an environment role, which is the functional change caused by the transformation of the package State protected            $_context;        Public Function SetContext (Context $context) {$this->_context = $context;            }//First elevator door open action public abstract function open ();            The elevator door is open, and of course it has closed public abstract function close ();            Elevator to cadres, run up public abstract function run ();        The elevator has to be able to stop and stop. Public abstract function Stop (); }/** * Environment class: Defines the interface that the customer is interested in.   Maintains an instance of the Concretestate subclass that defines the current state.        */class Context {//define all elevator state static $openningState = null;        static $closeingState = null;        static $runningState = null;            static $stoppingState = null;        Public Function __construct () {    Self:: $openningState = new Openningstate ();            Self:: $closeingState = new Closingstate ();            Self:: $runningState = new Runningstate ();            Self:: $stoppingState = new Stoppingstate ();            }//Set a current elevator state private $_liftstate;        Public Function Getliftstate () {return $this->_liftstate;            The Public Function setliftstate ($liftState) {$this->_liftstate = $liftState;        The current environment is notified to $this->_liftstate->setcontext ($this) in each implementation class;        Public Function open () {$this->_liftstate->open ();        Public function Close () {$this->_liftstate->close ();        Public Function Run () {$this->_liftstate->run ();        } Public Function Stop () {$this->_liftstate->stop (); }}/** * What to do when the elevator door is open */class Openningstate extends LiftstaTe {/** * Open course can be turned off, I just want to test the elevator door switch function * */Public Function close () {//state modification            $this->_context->setliftstate (context:: $closeingState);        The action is delegated to Closestate to execute the $this->_context->getliftstate ()->close ();      }//Open the elevator door public Function open () {output (' Lift open ... ');        }//door open elevator just want to run, this elevator, frighten you!        Public Function Run () {//do nothing;        }//The door is not stopped?        Public Function Stop () {//do nothing; }}/** * When the elevator door closed, the elevator can do what things * * Class Closingstate extends Liftstate {//elevator door closed, this is the shutdown status to achieve          Action Public Function close () {output (' Lift close ... '); }///elevator door closed and opened again, amuse you to play, that this permit Yes Public function open () {$this->_context->setliftstate (context:: $o  Penningstate);        Open the Door $this->_context->getliftstate ()->open (); }            //The elevator door closes and runs, which is normal. Public function run () {$this->_context->setliftstate (context:: $runningState);        set to run state; $this->_context->getliftstate ()->run (); }//The elevator door is closed, I will not press the floor public function stop () {$this->_context->setliftstate (context  :: $stoppingState);        set to stop state; $this->_context->getliftstate ()->stop (); }}/** * What actions can the elevator perform in the Running state */class Runningstate extends Liftstate {//elevator door closed? That's for sure. Public function Close () {//do-nothing}//Run the elevator door? You are crazy! The elevator won't give you public function open () {//do Nothing}//This is the method to be implemented in the Run state public functi      On run () {output (' Lift run ... '); }//This thing is absolutely reasonable, light operation does not stop who dares to do this elevator?! It's only God. Public function Stop () {$this->_context->setliftstate (context:: $stoppingState);//environment set to stop The state of being; $this->_context-> Getliftstate ()->stop (); }}/** * What can I do in a stopped state? */class Stoppingstate extends Liftstate {//stop status closed?        The elevator door was closed!        Public function Close () {//do nothing;        }//Stop state, open the door, that is!            Public Function open () {$this->_context->setliftstate (context:: $openningState);        $this->_context->getliftstate ()->open (); }//Stop state to run again, normal is public function run () {$this->_context->setliftstate (context:: $runningSt            ATE);        $this->_context->getliftstate ()->run (); }//How does the stop state occur?      Of course the Stop method executes the public function stop () {output (' Lift stop ... '); }}/** * Simulate elevator action */class Client {public static function test () {$context            = new Context ();                $context->setliftstate (New Closingstate ());            $context->open ();   $context->close ();         $context->run ();        $context->stop (); }} client::test ();
  • 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.