设计模式之简单工厂模式

Posted: 2015-10-08  By  vilay  |  Views(1614)

假如我们需要实现一个计算器功能,最原始简单的方法就是写一个简单的类

如下:

<?php
class Operator{
  public function getResult($numberA,$numberB,$operator)
    {
      if ($operator == '+') {
          $result = $numberA + $numberB;
        } elseif ($operaor == '-') {
          $result = $numberA-$numberB;
        } elseif ($operator == '*') {
          $result = $numberA * $numberB; 
        } elseif ($operator == '/') {
          $result = $numberA / $numberB; //仅作示范,分母为0不予考虑
        }
        return $result;
    }
}

以上代码足以实现功能,这样的代码是紧耦合的,但是我们可以使用设计模式使它更优化。

简单工厂模式实现:

运算类(Operator.class.php):

<?php
class Operator {
  public $numberA;
    public $numberB;
    public $result = 0;

    public function _set($name,$value)
    {
      $this->$name = $value;
    }

    public function _get($name)
    {
        return $this->$name;
    }

    public function getResult()
    {
      return $this->result;
    }
}

class OperatorAdd extends Operator{
  public function getResult()
    {
     $this->result = $this->numberA + $this->numberB;
     return $this->result;
    }
}

class OperatorSub extends Operator{
  public function getResult()
    {
     $this->result = $this->numberA - $this->numberB;
     return $this->result;
    }
}

class OperatorMul extends Operator{
  public function getResult()
    {
     $this->result = $this->numberA * $this->numberB;
     return $this->result;
    }
}

class OperatorDiv extends Operator{
  public function getResult()
    {
     $this->result = $this->numberA / $this->numberB;
     return $this->result;
    }
}

工厂类(Factory.php):

<?php
class Factory{
  public function createObject($operator)
    {
      switch($operator){
          case '+':
              $obj = new OperatorAdd();
                break;
            case '-':
              $obj = new OperatorSub();
                break;
            case '*':
              $obj = new OperatorMul();
                break;
            case '/':
                $obj = new OperatorDiv();
                break;
        }
        return $obj;
    }
}

客户端代码:

<?php
require 'Factory.php';
require 'Operator.class.php';
$numberA = isset($_POST['numberA']) : $_POST['numberA'] : 0;
$numberB = isset($_POST['numberB']) : $_POST['numberB'] : 0;
$operator = isset($_POST['operator']) : $_POST['operator'] : '+';
$factory = new Factory();
$obj = $factory->createObject($operator);
$obj->numberA = $numberA;
$ob->numberB = $numberB;
echo $obj->getResult();

我们就以简单工厂的方式实现了计算器功能,这样的程序简单易维护。达到了解耦的目的。