什么是工厂模式
组装一台电脑,需要不同的零件,而工厂模式就像零件制造商一样,不同的零件不同的工厂负责或者管理着不同的零件工厂,将代码进行解耦,不需要在逻辑代码中new不同的类,进行一个统一的管理。
工厂模式的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| <?php
/** * 一个运算方法的接口 * Interface Operation */ interface Operation { /** * 两个数的运算 * @param int $num1 * @param int $num2 * @return int */ public function getVal (int $num1, int $num2): int; }
/** * 加法 * Class Add */ class Add implements Operation { public function getVal(int $num1, int $num2): int { return $num1 + $num2; } }
/** * 减法 * Class Sub */ class Sub implements Operation { public function getVal(int $num1, int $num2): int { return $num1 - $num2; } }
/** * 运算工厂(工厂模式) * Class CounterFactory */ class CounterFactory { private static $operation;// 运算
/** * 创建一个运算 * @param string $operation * @return Add|Sub */ public static function createOperation (string $operation) { switch ($operation) { case '+': self::$operation = new Add(); break; case '-': self::$operation = new Sub(); break;
} return self::$operation; } }
$factory = CounterFactory::createOperation('+'); $res = $factory->getVal(1, 2); var_dump($res);
|