PHP设计模式入门之状态模式原理与实现方法分析(2)

index.php

<?php
require_once 'JuiceMachine.php';
 
$juiceMachine = new JuiceMachine(1);
 
$juiceMachine->insertCoin();
$juiceMachine->clickButton();

运行的结果是:

you just insert a coin
you clicked, we are giving you a bottle of juice...
now you get you juice
opps, runing out of juice

到目前为止我们的程序运行良好,没有出现什么问题,但是从这些多重的if判断中你是否嗅到了坏代码的味道呢?有一天问题终于出现了,老板希望当用户点击按钮时有10%的概率拿到两瓶饮料,我们需要为饮料机多加一个状态,这时去修改代码就成为了一种灾难,而且很可能会影响到之前的代码,带来新的bug,看看状态模式如何帮助我们度过难关吧!

状态模式的官方定义是:状态模式允许对象在内部状态改变是改变它的行为,对象看起来好像是修改了它的类

用uml类图表示如下:

在我们这个项目中的实际类图如下:

具体实现代码:

State.php

<?php
interface State{
  
  /**
   * 插入硬币
   */
  public function insertCoin();
  
  /**
   * 回退硬币
   */
  public function retreatCoin();
  
  /**
   * 点击按钮
   */
  public function clickButton();
  
  /**
   * 发放饮料
   */
  public function dispend();
}

NomoneyState.php

<?php
require_once 'State.php';
class NomoneyState implements State{
  
  /**
   * 饮料机的实例
   * 
   * @var object
   */
  private $_juiceMachine;
  
  /**
   * 构造方法,主要用于初始化饮料机实例
   * 
   */
  public function __construct($juiceMachine){
    $this->_juiceMachine = $juiceMachine;
  }
  
 /* (non-PHPdoc)
   * @see State::insertCoin()
   */
  public function insertCoin()
  {
    // TODO Auto-generated method stub
    echo "you just insert a coin<br />";
    //将饮料机的状态切换成有钱的状态
    $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<br />";
  }
 
 /* (non-PHPdoc)
   * @see State::clickButton()
   */
  public function clickButton()
  {
    // TODO Auto-generated method stub
    echo "you clicked,but you hav'nt inserted a coin yet<br />";
  }
 
 /* (non-PHPdoc)
   * @see State::dispend()
   */
  public function dispend()
  {
    // TODO Auto-generated method stub
    echo "you need to pay first<br />";
  }
}


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/3848.html