I Want to improve my knowledge about PHP Pattern and Architecture. I create a stupid example to use Factory Pattern
This is my Code:
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();
}
}
Where is the advanteges to use this approach ?
I could do it, to create Circle Object
$circle = new Circle(3);
echo $circle->getArea();
The Only Advantage that I can see with use Factory Pattern is that, I could don't know which Shape the user Want.
Aucun commentaire:
Enregistrer un commentaire