以下内容以一个简单的计算器程序作为案例分析。第一步,定义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; } } ?>
The second step is to define an interface, which declares the method to implement the operation
<?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(); ?>
The above introduces the PHP implementation of the simple factory pattern, including the content of the simple factory pattern. I hope it will be helpful to friends who are interested in PHP tutorials.