以下内容以一个简单的计算器程序作为案例分析。第一步,定义Operation,是一个父类,有两个属性,表示用于计算的两个参数。
<?php /* * 计算类 */ class Operation{ private $numA=0; private $numB=0; public function setNumA($numA) { $this->numA=$numA; } public function getNumA() { return $this->numA; } public function setNumB($numB) { $this->numB=$numB; } public function getNumB() { return $this->numB; } } ?>
第二步,定义一个接口,接口中声明实现运算的方法
<?php /* *工厂接口 */ interface InterOperate{ function getResult(); } ?>
<?php /** * 加法运算类 */ include_once "IOperate.php"; include_once 'Operation.php'; class OperationAdd extends Operation implements InterOperate { function getResult() { $result=$this->getNumA()+$this->getNumB(); return $result; } } ?>
<?php include_once "OperationAdd.php"; include_once "OperationMinus.php"; class SimpleFactory { static function createAdd() { return new OperationAdd; } static function createMinus() { return new OperationMinus; } } ?>
<?php /* * 客户端代码 */ include_once "OperationAdd.php"; include_once 'Operation.php'; include_once 'SimpleFactory.php'; $op=SimpleFactory::createAdd(); $op->setNumA(2); $op->setNumB(4); echo $op->getResult(); $om=SimpleFactory::createMinus(); $om->setNumA(45); $om->setNumB(34); echo "<br>"; echo $om->getResult(); ?>
以上就介绍了简单工厂模式之php实现,包括了简单工厂模式方面的内容,希望对PHP教程有兴趣的朋友有所帮助。