php写一个工厂模式
时间: 2023-02-22 11:09:24 浏览: 62
工厂模式是一种常用的设计模式,主要用于隔离对象的创建过程,以便简化程序结构。
在 PHP 中,可以使用工厂类来实现工厂模式。下面是一个简单的示例:
```
class ShapeFactory {
public static function createShape(string $shapeType): Shape {
if ($shapeType == "circle") {
return new Circle();
} else if ($shapeType == "rectangle") {
return new Rectangle();
} else if ($shapeType == "square") {
return new Square();
}
return null;
}
}
interface Shape {
public function draw();
}
class Circle implements Shape {
public function draw() {
// 实现圆形的绘制逻辑
}
}
class Rectangle implements Shape {
public function draw() {
// 实现矩形的绘制逻辑
}
}
class Square implements Shape {
public function draw() {
// 实现正方形的绘制逻辑
}
}
```
在上面的代码中,我们定义了一个 ShapeFactory 类,该类提供了一个静态方法 createShape,用于根据给定的形状类型创建对应的图形对象。
使用工厂模式可以简化代码结构,隔离对象创建过程,并且方便以后扩展。