俗话说的好:要想代码写得好,设计模式少不了(自己编的,哈哈!)。
今天我们来看一下两个设计模式:简单工厂模式和工厂方法模式。话不多说,我们用一个例子来分析。
题目:用PHP语言实现一个计算器控制台程序,要求输入两个数和运算符号,得到运算结果。
根据题目要求我们可以画出如下结构图:
<?php
abstract class OperatorService
{
private $numberA;
private $numberB;
public function setNumberA($num)
{
$this->numberA = $num;
}
public function setNumberB($num)
{
$this->numberB = $num;
}
public function getNumberA()
{
return $this->numberA;
}
public function getNumberB()
{
return $this->numberB;
}
abstract function getResult();
}
加法运算类:
<?php
namespace App\Service\Operate;
class OperateAddService extends OperatorService
{
public function getResult()
{
$result = $this->getNumberA() $this->getNumberB();
return $result;
}
}
减法运算类:
<?php
namespace App\Service\Operate;
class OperateSubService extends OperatorService
{
public function getResult()
{
$result = $this->getNumberA() - $this->getNumberB();
return $result;
}
}
乘法运算类:
<?php
namespace App\Service\Operate;
class OperateMulService extends OperatorService
{
public function getResult()
{
$result = $this->getNumberA() * $this->getNumberB();
return $result;
}
}
除法运算类:
<?php
namespace App\Service\Operate;
class OperateDivService extends OperatorService
{
public function getResult()
{
if (!empty($this->getNumberB())) {
$result = $this->getNumberA() / $this->getNumberB();
} else {
$result = '错误';
}
return $result;
}
}
以上基础的运算方法类都已经实现了,那么我们就可以实现简单工厂类啦。
<?php
namespace App\Service\Operate;
class OperateFactory
{
public static function dealWithOperator($params)
{
$operator = $params['operator'];
switch ($operator) {
case ' ':
$service = new OperateAddService();
break;
case '-':
$service = new OperateSubService();
break;
case '*':
$service = new OperateMulService();
break;
case '/':
$service = new OperateDivService();
break;
default:
break;
}
return $service;
}
}
好啦,简单工厂模式就介绍完啦,通过例子介绍是不是更加清晰明了呢。
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved