php- state mode

scenes to be used:
When different states dependent code logic to handle different logic states are determined and the required number, the logic state of each process is also complicated, this time it should consider using a design pattern state. Avoid too many if else appears. Of course, the code will be very simple.
If less state and logic is very simple, I think there is no need to use the state model, after all, need to create a state model is a waste of a lot of files feeling.
application:
I'll give you an example, so as to deepen the impression of it. Take inventory status we camped return to judge the error condition is good. Although the probability of use is not real big, but a better understanding of it.

//
create a state of the abstract class abstract class State { abstract public function getErrorTip(ReserveResultHandler $r); } // shortage of stock on behalf of the state to create a class of class NoStockState the extends State { public function getErrorTip ( ReserveResultHandler $ r ) { IF ( $ R & lt -> == statusCode. 1 ) { echo 'inadequate merchandise inventory !!! " ; } else { $r->setState(new NoAreaState()); $r->getErrorTip(); } } } // create state no longer represents the region-wide class class NoAreaState the extends State { public function getErrorTip ( ReserveResultHandler $ r ) { IF ( $ R & lt -> statusCode == 2 ) { echo 'of the active region are not!' ; } else { $r->setState(new ExpireSate()); $r->getErrorTip(); } } }
// Create a state representative of a timeout-based
class ExpireSate the extends State
{
  public function getErrorTip ( ReserveResultHandler $ R & lt )
  {
    IF ( $ R-> == statusCode. 3 ) {
      echo 'event is expired! " ;
    }
  }
}
// Preemption result handler class class ReserveResultHandler { public $statusCode; private $current; public function __construct($params) { $this->statusCode = $params; $this->current = new NoStockState(); } public function setState(State $s) { $this->current = $s; } public function getErrorTip () { $this->current->getErrorTip($this); } } // The following code just to test real time applications such as inventory, then camped at a single time, that the following code will write the next one logical flow in. Those in front of a class defined in a file $ r = new new ReserveResultHandler (1 ); $ r -> getErrorTip (); // result: lack of merchandise inventory !!! R & lt $ -> statusCode = 2 ; $ R & lt -> getErrorTip (); // Result: not in the active region !!! r $ -> statusCode = 3 ; $ r -> getErrorTip (); // Result: The event is expired!

 

Guess you like

Origin www.cnblogs.com/mantianxing/p/11099258.html