设计模式-简单工厂模式

78 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

最近在看程杰的《大话设计模式》,感觉此书不错,打算用PHP语音来总结相关的设计模式。之后会根据自身理解再次进行修改。 最好买这本书对照着看,要不然光看下边的代码可能理解的不是很好 以下程序就不针对命名等规范做更多解释; 以下程序不考虑特殊情况,都是正常数据运行程序;

案例:计算器控制程序 小菜的程序

class Program {
  public function getResult($stringA, $stringB, $stringC)
  {
    $stringD = '';

    switch ($stringB){
      case '+':
        $stringD = $stringA + $stringC;
        break;
      case '-':
        $stringD = $stringA - $stringC;
        break;
      case '*':
        $stringD = $stringA * $stringC;
        break;
      case '/':
        $stringD = $stringA / $stringC;
        break;
    }

    echo $stringD;
  }
}

$Program = new Program();
$Program->getResult(5, '/', 3);

简单工厂模式(Simple Factory Pattern):又称为静态工厂方法(Static Factory Method)模式,它属于类创建型模式。在简单工厂模式中,可以根据参数的不同返回不同类的实例。简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。

简单工厂模式代码:

//运算类
class Operation {
  protected $_numberA = 0;
  protected $_numberB = 0;

  public function nubmerA($num)
  {
    $this->_numberA = $num;
  }

  public function nubmerB($num)
  {
    $this->_numberB = $num;
  }

  public function getResult()
  {
    $result = 0;
    return $result;
  }
}

//加法类 继承运算类
class OperstionAdd extends Operation {
  public function getResult()
  {
    $result = $this->_numberA + $this->_numberB;
    return $result;
  }
}
//减法类 继承运算类
class OperstionSub extends Operation {
  public function getResult()
  {
    $result = $this->_numberA - $this->_numberB;
    return $result;
  }
}
//乘法类 继承运算类
class OperstionMul extends Operation {
  public function getResult()
  {
    $result = $this->_numberA * $this->_numberB;
    return $result;
  }
}
//除法类 继承运算类
class OperstionDiv extends Operation {
  public function getResult()
  {
    $result = $this->_numberA / $this->_numberB;
    return $result;
  }
}

//简单运算工厂类
class OperationFactory{
  public function createOperation($operate)
  {
    $oper = '';
    switch ($operate){
      case '+':
        $oper = new OperstionAdd();
        break;
      case '-':
        $oper = new OperstionSub();
        break;
      case '*':
        $oper = new OperstionMul();
        break;
      case '/':
        $oper = new OperstionDiv();
        break;
    }
    return $oper;
  }
}

//客户端代码实现
$OperationFactory = new OperationFactory();
$oper = $OperationFactory->createOperation('*');
$oper->nubmerA(4);
$oper->nubmerB(6);
echo $oper->getResult();

注:简单工厂模式用于实例化合适的类对象。总结一下适用场景: (1)需要创建的对象较少。 (2)客户端不关心对象的创建过程。