PHP Factory Method mode
<?php/** * Factory method mode, define an interface for creating objects, and let subclasses decide which class to instantiate. The factory method pattern defers the instantiation of a class to its subclasses. * * Contains the object * 1, abstract product * 2, specific product * 3, Abstract Factory * 4, specific factory * * Abstract the factory class of the simple Factory mode, avoiding the need to modify the plant in the simple Factory mode when expanding Class. Easy to expand and maintain. **//** * Operation class **/abstract class Operation {Abstract public Function getValue ($num 1,$ NUM2); }/** * Addition class **/class Operationplus extends Operation {public Function getValue ($num 1 , $num 2) {return $num 1 + $num 2; }}/** * Subtraction classes **/class Operationsub extends Operation {public function GetValue ($num 1, $num 2) {return $num 1-$num 2; }}/** * Multiplication classes **/class Operationmul extends Operation {public function GetValue ($num 1, $num 2) {return $num 1 * $num 2; }}/** * Division classes **/Class Operationdiv extends Operation {PubLic function GetValue ($num 1, $num 2) {try {if ($num 2 = = 0) {throw NE W Exception (' divisor cannot be 0! '); } else {return $num 1/$num 2; }} catch (Exception $e) {echo $e->getmessage (); }}}/** * Abstract factory class **/abstract class Factory {public abstract function Getoperation (); }/** * Addition factory **/class Factoryplus extends Factory {public Function getoperation () { return new Operationplus (); }}/** * Addition factory **/class Factorysub extends Factory {public Function Getoperatio N () {return new operationsub (); }}/** * Addition factory **/class Factorymul extends Factory {public Function Getoperatio N () {return new Operationmul (); } }/** * Addition factory **/class Factorydiv extends Factory {public Function getoperation () { return new Operationdiv (); }}//addition $factory = new Factoryplus (); $operation = $factory->getoperation (); echo $operation->getvalue (10,11); Subtraction $factory = new Factorysub (); $operation = $factory->getoperation (); echo $operation->getvalue (10,11); Division $factory = new Factorydiv (); $operation = $factory->getoperation (); echo $operation->getvalue (10,2); ?>