工厂模式
工厂模式
工厂模式属于创建型模式,定义了一个用于创建对象的接口,让子类决定实例化哪一个类。工厂模式使一个类的实例化延迟到其子类
模拟场景:实现一个计算器的多种运算功能
下面代码演示:
autoload.php
12345678910111213 | <?phpfunction classLoader($class){ $path = str_replace('\', DIRECTORY_SEPARATOR, $class); $file = __DIR__ . DIRECTORY_SEPARATOR . $path . '.php'; if (file_exists($file)) { require_once $file; }}spl_autoload_register('classLoader'); |
具体运算类代码 Operation.php
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 | <?phprequire_once "OperationInterface.php";/** * Class Add * @package DesignPatternsSimpleFactory */class Add implements OperationInterface{ /** * @param $a * @param $b * @return mixed */ public function result($a, $b) { return $a + $b; }}/** * Class Sub * @package DesignPatternsSimpleFactory */class Sub implements OperationInterface{ /** * @param $a * @param $b * @return mixed */ public function result($a, $b) { return $a - $b; }}/** * Class Mul * @package DesignPatternsSimpleFactory */class Mul implements OperationInterface{ /** * @param $a * @param $b * @return mixed */ public function result($a, $b) { return $a * $b; }}/** * Class Div * @package DesignPatternsSimpleFactory */class Div implements OperationInterface{ /** * @param $a * @param $b * @return mixed */大专栏 【设计模式】工厂模式"> public function result($a, $b) { if ($b == 0) return "除数不能为0"; return $a / $b; }} |
工厂接口代码 FactoryInterface.php
12345678910 | <?php/** * Interface FactoryInterface */interface FactoryInterface{ public static function createOperation();} |
加法工厂类 AddFactory.php
12345678910111213141516 | <?phprequire_once "Operation.php";/** * Class AddFactory */class AddFactory implements FactoryInterface{ public static function createOperation() { return new Add(); }} |
减法工厂类 SubFactory.php
123456789101112131415 | <?phprequire_once "Operation.php";/** * Class SubFactory */class SubFactory implements FactoryInterface{ public static function createOperation() { return new Sub(); }} |
乘法工厂类 MulFactory.php
123456789101112131415 | <?phprequire_once "Operation.php";/** * Class MulFactory */class MulFactory implements FactoryInterface{ public static function createOperation() { return new Mul(); }} |
除法工厂类 DivFactory.php
1234567891011121314 | <?phprequire_once "Operation.php";/** * Class DivFactory */class DivFactory implements FactoryInterface{ public static function createOperation() { return new Div(); }} |
优点
工厂模式克服了简单工厂模式违背开放-封闭的原则,同时保留了简单工厂模式的优点
缺点
每增加一个产品,就需要增加一个产品工厂的类,增加了额外的开发量