简单的一个php工厂模式代码
程序员文章站
2022-03-30 13:25:33
...
1. [PHP]代码
<?php // factory pattern class Shape { static public function getShape($type, $dimension) { if ($type && $dimension) { switch($type) { case 'circle': return new Circle($dimension); break; case 'square': return new Square($dimension); break; default: throw new Exception("Unrecognized shape"); break; } } } } class Circle { private $radius = 0; public function __construct($radius) { $this->radius = $radius; } public function getArea() { return $this->radius * $this->radius * pi(); } } class Square { private $side = 0; public function __construct($side) { $this->side = $side; } public function getArea() { return $this->side * $this->side; } } $shape = Shape::getShape('circle', 10); echo $shape->getArea(); echo "\n"; $shape = Shape::getShape('square', 2); echo $shape->getArea(); echo "\n";
上一篇: php语法学习
下一篇: Nginx设置前后端分离实例代码