<?php/* Example 2: *///simple Factory mode/* * Define operation Class */abstract class operation {protected $_numbera = 0;protected $_numberb = 0;protected $_result = 0;Public function __construct ($A, $B) {$this->_numbera = $A;$this->_numberb = $B;}Public Function Setnumber ($A, $B) {$this->_numbera = $A;$this->_numberb = $B;}/* protected function Clearresult () {$this->_result = 0;} */Public Function Clearresult () {return $this->_result = 0;}Abstract method without method bodyAbstract protected function getresult ();}//Inherit an abstract class, the subclass must implement all abstract methods in the abstract class;//In addition, the visibility of these methods must be the same as in the abstract class (or looser) class Operationadd extends operation {Public Function GetResult () {$this->_result= $this->_numbera + $this->_numberb;return $this->_result;}} class Operationsub extends operation {Public Function GetResult () {$this->_result= $this->_numbera-$this->_numberb;return $this->_result;}} class Operationmul extends operation {Public Function GetResult () {$this->_result= $this->_numbera * $this->_numberb;return $this->_result;}} class Operationdiv extends operation {Public Function GetResult () {$this->_result= $this->_numbera/$this->_numberb;return $this->_result;}} class Operationfactory {To create a static member variable that holds an instanceprivate static $obj;Create a public static method that accesses an instancepublic static function CreateOperation ($type, $A, $B) {Switch ($type) {Case ' + ':Self:: $obj = new Operationadd ($A, $B);BreakCase '-':Self:: $obj = new Operationsub ($A, $B);BreakCase ' * ':Self:: $obj = new Operationmul ($A, $B);BreakCase '/':Self:: $obj = new Operationdiv ($A, $B);Break}Return self:: $obj;}}/* $obj = operationfactory::createoperation (' + '); $obj->setnumber (bis); */$obj = operationfactory::createoperation (' * ', 5,6); Echo $obj->getresult ();30echo "<br/>", Echo $obj->clearresult ();0echo ' <br> ';/* echo $obj->_result; */
Simple--factory--abstract