我正在考虑使用工厂模式来创建不同的对象。但是如果通过工厂模式在另一个类中创建对象使得紧密耦合或不紧密耦合,我有点混淆。例如:
class CarFactory
{
public static function createCar($type)
{
if ($type == 'sport') {
return new SportCar();
} elseif ($type == 'LuxuryCar' {
return new LuxuryCar();
}
}
}
interface Vehicle
{
public function drive();
}
class SportCar implements Vehicle
{
$speed = 'very fast';
public function drive()
{
return ' is driving sport car';
}
}
class LuxuryCar implements Vehicle
{
$speed = 'normal';
public function drive()
{
return ' is driving luxury car';
}
}
class DrivingApplication
{
public function __constructor($driverName, $carType)
{
$car = CarFactory::createCar($carType); //<------ HERE//
echo $driverName . $car->drive();
}
}
$app = new DrivingApplication();
因此,在DrivingApplication类中,我使用CarFactory创建了一个汽车类。我的问题是:
答案 0 :(得分:0)
嗯,new
必须被称为某处。您可以通过使用CarFactory::$classes
数组将类型映射到类来尝试使其更具动态性:
class CarFactory {
public static $classes = [];
public static function create ( $type ) {
$class = static::$classes[$type];
return new $class();
}
}
然后您可以在运行时添加汽车类型。
CarFactory::$classes['foo'] = 'FooClass';
$foo = CarFactory::create('foo');