如何使用PHP面向对象简单工厂模式创建灵活的对象实例
简单工厂模式是一种常见的设计模式,它可以在不暴露对象创建逻辑的情况下创建对象实例。这种模式可以提高代码的灵活性和可维护性,特别适用于需要根据输入条件动态创建不同对象的场景。在PHP中,我们可以利用面向对象编程的特性来实现简单工厂模式。
下面我们来看一个例子,假设我们需要创建一个图形计算器,能够根据用户输入的形状类型(圆形、正方形、三角形等)来计算相应的面积和周长。
首先,我们需要创建一个抽象类Shape来表示各种形状:
'abstract class Shape
{
abstract public function getArea();
abstract public function getPerimeter();
}
然后,我们创建具体的形状类,比如圆形类Circle、正方形类Square和三角形类Triangle:
'class Circle extends Shape
{
private $radius;
public function __construct($radius)
{
$this->radius = $radius;
}
public function getArea()
{
return pi() * pow($this->radius, 2);
}
public function getPerimeter()
{
return 2 * pi() * $this->radius;
}
}
class Square extends Shape
{
private $side;
public function __construct($side)
{
$this->side = $side;
}
public function getArea()
{
return pow($this->side, 2);
}
public function getPerimeter()
{
return 4 * $this->side;
}
}
class Triangle extends Shape
{
private $side1;
private $side2;
private $side3;
public function __construct($side1, $side2, $side3)
{
$this->side1 = $side1;
$this->side2 = $side2;
$this->side3 = $side3;
}
public function getArea()
{
// 使用海伦公式计算面积
$semiPerimeter = ($this->side1 + $this->side2 + $this->side3) / 2;
return sqrt($semiPerimeter * ($semiPerimeter - $this->side1) *
($semiPerimeter - $this->side2) * ($semiPerimeter - $this->side3));
}
public function getPerimeter()
{
return $this->side1 + $this->side2 + $this->side3;
}
}
接下来,我们创建一个简单工厂类ShapeFactory,根据用户输入的形状类型来创建相应的对象实例:
'class ShapeFactory
{
public static function createShape($type, $params)
{
switch ($type) {
case 'circle':
return new Circle($params['radius']);
case 'square':
return new Square($params['side']);
case 'triangle':
return new Triangle($params['side1'], $params['side2'], $params['side3']);
default:
throw new Exception('Unsupported shape type: ' . $type);
}
}
}
现在,我们可以使用简单工厂模式来创建图形对象了。例如,我们可以创建一个圆形对象并计算其面积和周长:
'$params = ['radius' => 5];
$shape = ShapeFactory::createShape('circle', $params);
echo 'Area of the circle: ' . $shape->getArea() . PHP_EOL;
echo 'Perimeter of the circle: ' . $shape->getPerimeter() . PHP_EOL;
输出结果为:
'Area of the circle: 78.539816339745
Perimeter of the circle: 31.415926535897
同样地,我们也可以创建正方形和三角形对象,并计算它们的面积和周长。
通过使用面向对象的简单工厂模式,我们可以根据用户的输入动态创建不同的对象实例,而无需暴露对象的创建逻辑和细节。这样可以使我们的代码更加灵活和易于维护。在实际开发中,如果遇到需要根据条件创建不同对象的情况,你可以考虑使用简单工厂模式来实现。