I'm thinking to use a factory pattern to create different objects. But I'm a bit confuse if creating objects inside another class via factory pattern make tightly coupled or not. For example:
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();
So, inside the DrivingApplication class, I created a car class using CarFactory. My question is:
- does it still assume tight coupling??
- Should I create car object outside the DrivingApplication class and use dependency injection to solve tight coupling??
- what if I can only identify which car type to create inside the DrivingApplication class??