Laravel 的抽象工厂设计模式代码看起来大致像这样:
<?phpnamespace App\Factories;
use App\Contracts\Shape;
interface ShapeFactory
{
public function makeCircle(): Shape;
public function makeRectangle(): Shape;
public function makeSquare(): Shape;
}
class CircleFactory implements ShapeFactory
{
public function makeCircle(): Shape
{
return new Circle;
}
public function makeRectangle(): Shape
{
throw new \Exception('This factory can only make circles.');
}
public function makeSquare(): Shape
{
throw new \Exception('This factory can only make circles.');
}
}
class RectangleFactory implements ShapeFactory
{
public function makeCircle(): Shape
{
throw new \Exception('This factory can only make rectangles.');
}
public function makeRectangle(): Shape
{
return new Rectangle;
}
public function makeSquare(): Shape
{
throw new \Exception('This factory can only make rectangles.');
}
}
class SquareFactory implements ShapeFactory
{
public function makeCircle(): Shape
{
throw new \Exception('This factory can only make squares.');
}
public function makeRectangle(): Shape
{
throw new \Exception('This factory can only make squares.');
}
public function makeSquare(): Shape
{
return new Square;
}
}
在这个例子中,我们定义了一个 ShapeFactory
接口和三个具体的工厂类,分别是 CircleFactory
、RectangleFactory
和 SquareFactory
。这三个工厂类都实现了 ShapeFactory
接口,并定义了如何创建圆形、矩形和正方形。
使用这些工厂类的方式如下:
$circleFactory = new CircleFactory;
$circle = $circleFactory->makeCircle();
$rectangleFactory = new RectangleFactory;
$rectangle = $rectangleFactory->makeRectangle();
$squareFactory = new SquareFactory;
$square = $squareFactory->makeSquare();
抽象工厂模式是一种创建型设计模式,它通过定义一个抽象工厂接口来创建一系列相关的产品,而不需要指定它