【发布时间】:2016-05-13 21:37:21
【问题描述】:
我想提高我对 PHP 模式和体系结构的了解。 我创建了一个使用工厂模式的愚蠢示例
这是我的代码:
index.php
$shape = Shape::getShape('circle', 3);
echo $shape->getArea();
shapes.php
class Shape
{
public static function getShape($type, $num)
{
switch ($type) {
case 'circle':
return new Circle($num);
break;
case 'square':
return new Square($num);
break;
default:
throw new Exception("Unrecognized shape");
}
}
}
abstract class Form{
abstract public function getArea();
}
class Circle extends Form{
protected $_type = "Circle";
private $area;
/**
* circle constructor.
* @param $area
*/
public function __construct($area)
{
$this->area = $area;
}
public function getArea(){
return $this->area*pi();
}
}
使用这种方法的优势在哪里?
我可以做到,创建圆形对象
$circle = new Circle(3);
echo $circle->getArea();
我可以看到使用工厂模式的唯一优势是,我不知道用户想要哪种形状。
【问题讨论】:
标签: php design-patterns factory-pattern