Рубрики
Uncategorized

Анализ принципа режима состояния и метода реализации внедрения шаблона проектирования PHP

Автор оригинала: David Wong.

В этой статье описывается принцип и реализация шаблона состояния шаблонов проектирования PHP. Для вашей справки приведем следующие сведения:

Все, должно быть, пользовались автоматической питьевой машиной. Вставьте монеты или банкноты и выберите напиток, который вы хотите, и напиток выкатится под машину. Есть ли у вас какие-либо соответствующие, если вы используете программу для написания автомата для напитков, как этого добиться?

Прежде всего, мы можем разделить несколько состояний этой машины для напитков

1. Состояние отсутствия денег

2. Состояние богатства

3、 Статус продажи

4、 Статус распродано

Хорошо, узнав эти состояния, мы начинаем писать код!

Машина для сока. php

_count = $count;
   //When the number of drinks in the beverage machine is greater than zero, reset the status of the beverage machine to the state of no money.
   if($this->_count > 0){
     $this->_state = JuiceMachine::NOMONEY;
   }
 }
 
 /**
 *Put in coins
 */
 public function insertCoin(){
   if($this->_state == JuiceMachine::HASMONEY ){
     echo "you can't insert another coin!
"; }elseif($this->_state == JuiceMachine::NOMONEY){ echo "you just insert a coin
"; $this->_state = JuiceMachine::HASMONEY; }elseif($this->_state == JuiceMachine::SOLD){ echo "wait a minute, we are giving you a bottle of juice
"; }elseif($this->_state == JuiceMachine::SOLDOUT){ echo "you can't insert coin, the machine is already soldout
"; } } /** *Return coins */ public function retreatCoin(){ if($this->_state == JuiceMachine::HASMONEY ){ echo "coin return!
"; $this->_state = JuiceMachine::NOMONEY; }elseif($this->_state == JuiceMachine::NOMONEY){ echo "you have'nt inserted a coin yet
"; }elseif($this->_state == JuiceMachine::SOLD){ echo "sorry, you already clicked the botton
"; }elseif($this->_state == JuiceMachine::SOLDOUT){ echo "you have'nt inserted a coin yet
"; } } /** *Click the corresponding button of beverage */ public function clickButton(){ if($this->_state == JuiceMachine::HASMONEY ){ echo "you clicked, we are giving you a bottle of juice...
"; $this->_ State = judge machine:: sell; // change the status of the beverage machine to the sold mode $this->dispend(); }elseif($this->_state == JuiceMachine::NOMONEY){ echo "you clicked,but you hav'nt inserted a coin yet
"; }elseif($this->_state == JuiceMachine::SOLD){ echo "click twice does'nt get you two bottle of juice
"; }elseif($this->_state == JuiceMachine::SOLDOUT){ echo "you clicked, but the machine is already soldout
"; } } /** *Distribute drinks */ public function dispend(){ if($this->_state == JuiceMachine::HASMONEY ){ echo "please click the button first
"; }elseif($this->_state == JuiceMachine::NOMONEY){ echo "you need to pay first
"; }elseif($this->_state == JuiceMachine::SOLD){ echo "now you get you juice
"; //The number of drinks in the dispenser minus one $this->_count--; if($this->_count <= 0){ echo "opps, runing out of juice
"; //If there is no beverage in the beverage machine at this time, reset the status of the beverage machine to sold out $this->_state = JuiceMachine::SOLDOUT; }else{ //Reset the status of the beverage machine to no money $this->_state = JuiceMachine::NOMONEY; } }elseif($this->_state == JuiceMachine::SOLDOUT){ //In fact, this should not happen echo "opps, it appears that we don't have any juice left
"; } } }

Машина для сока. php

insertCoin();
$juiceMachine->clickButton();

Результаты операции заключаются в следующем:

вы просто вставляете монету, которую нажали, и мы даем вам бутылку сока… теперь у тебя есть соковые противники, у которых кончается сок

До сих пор наша программа работала хорошо без каких-либо проблем, но чувствуете ли вы запах плохого кода от этих многочисленных суждений if? В один прекрасный день проблема, наконец, появилась. Босс надеется, что, когда пользователь нажимает на кнопку, вероятность получения двух бутылок напитков составляет 10%. Нам нужно добавить дополнительное состояние в машину для напитков. В это время изменение кода становится катастрофой, что может повлиять на предыдущий код и привести к новым ошибкам. Давайте посмотрим, как режим штата может помочь нам преодолеть трудности!

Официальное определение шаблона состояния таково: режим состояния позволяет объекту изменять свое внутреннее состояние, изменяя его поведение, и объект выглядит так, как будто он изменил свой класс

Диаграмма классов UML выглядит следующим образом:

Фактическая диаграмма классов в нашем проекте выглядит следующим образом:

Конкретный код реализации:

Конкретный код реализации:

Конкретный код реализации:

_juiceMachine = $juiceMachine;
  }
  
 /* (non-PHPdoc)
   * @see State::insertCoin()
   */
  public function insertCoin()
  {
    // TODO Auto-generated method stub
    echo "you just insert a coin
"; //Switch the status of the beverage machine to the state of money $this->_juiceMachine->setState($this->_juiceMachine->getHasmoneyState()); } /* (non-PHPdoc) * @see State::retreatCoin() */ public function retreatCoin() { // TODO Auto-generated method stub echo "you have'nt inserted a coin yet
"; } /* (non-PHPdoc) * @see State::clickButton() */ public function clickButton() { // TODO Auto-generated method stub echo "you clicked,but you hav'nt inserted a coin yet
"; } /* (non-PHPdoc) * @see State::dispend() */ public function dispend() { // TODO Auto-generated method stub echo "you need to pay first
"; } }

Конкретный код реализации:

_juiceMachine = $juiceMachine;
  }
  
  /*
   * (non-PHPdoc) @see State::insertCoin()
   */
  public function insertCoin()
  {
    // TODO Auto-generated method stub
    echo "you can't insert another coin!
"; } /* * (non-PHPdoc) @see State::retreatCoin() */ public function retreatCoin() { // TODO Auto-generated method stub echo "coin return!
"; $this->_juiceMachine->setState($this->_juiceMachine->getNomoneyState()); } /* * (non-PHPdoc) @see State::clickButton() */ public function clickButton() { // TODO Auto-generated method stub echo "you clicked, we are giving you a bottle of juice...
"; //Change the status of the beverage machine to sell mode $rand = mt_rand(0, 0); //When the random number is 0 (i.e. 1 / 10 probability) and there is more than 1 bottle of beverage in the beverage machine if ($rand == 0 && $this->_juiceMachine->getCount() > 1) { $this->_juiceMachine->setState($this->_juiceMachine->getWinnerState()); } else { $this->_juiceMachine->setState($this->_juiceMachine->getSoldState()); } } /* * (non-PHPdoc) @see State::dispend() */ public function dispend() { // TODO Auto-generated method stub echo "please click the button first
"; } }

Конкретный код реализации:

_juiceMachine = $juiceMachine;
  }
  
 /* (non-PHPdoc)
   * @see State::insertCoin()
   */
  public function insertCoin()
  {
    // TODO Auto-generated method stub
    echo "you can't insert coin, the machine is already soldout
"; } /* (non-PHPdoc) * @see State::retreatCoin() */ public function retreatCoin() { // TODO Auto-generated method stub echo "you have'nt inserted a coin yet
"; } /* (non-PHPdoc) * @see State::clickButton() */ public function clickButton() { // TODO Auto-generated method stub echo "you clicked, but the machine is already soldout
"; } /* (non-PHPdoc) * @see State::dispend() */ public function dispend() { // TODO Auto-generated method stub echo "opps, it appears that we don't have any juice left
"; } }

Конкретный код реализации:

_juiceMachine = $juiceMachine;
  }
  
 /* (non-PHPdoc)
   * @see State::insertCoin()
   */
  public function insertCoin()
  {
    // TODO Auto-generated method stub
    echo "wait a minute, we are giving you a bottle of juice
"; } /* (non-PHPdoc) * @see State::retreatCoin() */ public function retreatCoin() { // TODO Auto-generated method stub echo "sorry, you already clicked the botton
"; } /* (non-PHPdoc) * @see State::clickButton() */ public function clickButton() { // TODO Auto-generated method stub echo "click twice does'nt get you two bottle of juice
"; } /* (non-PHPdoc) * @see State::dispend() */ public function dispend() { $this->_juiceMachine->decJuice(); if($this->_juiceMachine->getCount() <= 0){ echo "opps, runing out of juice
"; //If there is no beverage in the beverage machine at this time, reset the status of the beverage machine to sold out $this->_juiceMachine->setState($this->_juiceMachine->getSoldoutState()); }else{ //Reset the status of the beverage machine to no money $this->_juiceMachine->setState($this->_juiceMachine->getNomoneyState()); } } }

Конкретный код реализации:

_juiceMachine = $juiceMachine;
  }
  
  /*
   * (non-PHPdoc) @see State::insertCoin()
   */
  public function insertCoin()
  {
    // TODO Auto-generated method stub
    echo "wait a minute, we are giving you a bottle of juice
"; } /* * (non-PHPdoc) @see State::retreatCoin() */ public function retreatCoin() { // TODO Auto-generated method stub echo "sorry, you already clicked the botton
"; } /* * (non-PHPdoc) @see State::clickButton() */ public function clickButton() { // TODO Auto-generated method stub echo "click twice does'nt get you two bottle of juice
"; } /* * (non-PHPdoc) @see State::dispend() */ public function dispend() { echo "you are a winner! you get two bottle of juice!
"; $this->_juiceMachine->decJuice(); if ($this->_juiceMachine->getCount() > 0) { $this->_juiceMachine->decJuice(); if ($this->_juiceMachine->getCount() <= 0) { echo "opps, runing out of juice
"; //If there is no beverage in the beverage machine at this time, reset the status of the beverage machine to sold out $this->_juiceMachine->setState($this->_juiceMachine->getSoldoutState()); } else { //Reset the status of the beverage machine to no money $this->_juiceMachine->setState($this->_juiceMachine->getSoldoutState()); } } else { echo "opps, runing out of juice
"; //If there is no beverage in the beverage machine at this time, reset the status of the beverage machine to sold out $this->_juiceMachine->setState($this->_juiceMachine->getSoldoutState()); } } }

Конкретный код реализации:

_state = new SoldoutState($this);
    $this->_count = $count;
    //When the number of drinks in the beverage machine is greater than zero, reset the status of the beverage machine to the state of no money.
    if ($this->_count > 0) {
      $this->_state = new NomoneyState($this);
    }
  }
  
  /*
   * (non-PHPdoc) @see State::insertCoin()
   */
  public function insertCoin()
  {
    // TODO Auto-generated method stub
    $this->_state->insertCoin();
  }
  
  /*
   * (non-PHPdoc) @see State::retreatCoin()
   */
  public function retreatCoin()
  {
    // TODO Auto-generated method stub
    $this->_state->retreatCoin();
  }
  
  /*
   * (non-PHPdoc) @see State::clickButton()
   */
  public function clickButton()
  {
    $this->_state->clickButton();
    //In fact, the candy is distributed inside the machine after the user clicks the button, so there is no need to write a distribute method
    $this->_state->dispend();
  }
  
  /**
   *Set the status of the candy machine
   * 
   * @param State $state
   */
  public function setState(State $state)
  {
    $this->_state = $state;
  }
  
  /**
   *Get the status of no money
   */
  public function getNomoneyState(){
    return new NomoneyState($this);
  }
  
  /**
   *Get rich
   */
  public function getHasmoneyState(){
    return new HasmoneyState($this);
  }
  
  /**
   *Get sold status
   */
  public function getSoldState(){
    return new SoldState($this);
  }
  
  /**
   *Get sold out status
   */
  public function getSoldoutState(){
    return new SoldoutState($this);
  }
  
  /**
   *Get the status of the lucky
   */
  public function getWinnerState(){
    return new WinnerState($this);
  }
  
  /**
   *Get the number of drinks in the dispenser
   */
  public function getCount(){
    return $this->_count;
  }
  
  /**
   *Reduce the number of drinks by one
   */
  public function decJuice(){
    echo "now you get you juice
"; //The number of drinks in the dispenser minus one $this->_count--; } }

Конкретный код реализации:

insertCoin();
$juiceMachine->clickButton();

Подробнее о содержании, связанном с PHP заинтересованные читатели могут ознакомиться с этой темой сайта: “Вводный учебник по объектно-ориентированному программированию PHP”, “Навыки работы с массивом PHP (массив)”, “Вводный курс по основному синтаксису PHP”, “Краткое описание операций PHP и использования операторов”, “Краткое описание использования символьной строки (строки) PHP”, “Руководство по вводу в работу с базой данных PHP + MySQL” и “Общая работа с базой данных PHP” Краткое описание навыков написания

Я надеюсь, что эта статья поможет вам в программировании на PHP.