设计模式-简单工厂模式

最近在看程杰的《大话设计模式》,感觉此书不错,打算用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)客户端不关心对象的创建过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PeakXin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值