以下是一个使用PHP实现静态工厂模式的实例,通过静态方法创建对象,以简化对象的创建过程。

实例:创建不同类型的汽车

在这个例子中,我们将创建一个汽车类,并根据不同的车型创建汽车对象。

实例静态工厂php,实例静态工厂PHP模式应用详解  第1张

汽车类

```php

class Car {

protected $type;

public function __construct($type) {

$this->type = $type;

}

public function getType() {

return $this->type;

}

}

```

静态工厂类

```php

class CarFactory {

public static function createCar($type) {

switch ($type) {

case 'SUV':

return new Car('SUV');

case 'Sedan':

return new Car('Sedan');

case 'Convertible':

return new Car('Convertible');

default:

throw new Exception("