2

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??
agthumoe
  • 119
  • 1
  • 11
  • Why would you not call the factory class `VehicleFactory`? Hard to answer your question without seeing calling classes/code. This might actually be better suited question for codereview.stackexchange.com – Mike Brant Oct 15 '14 at 18:52

1 Answers1

1

Well, new has to be called somewhere. You can try making it a bit more dynamic by having a CarFactory::$classes array that maps types to classes:

class CarFactory {
    public static $classes = [];
    public static function create ( $type ) {
        $class = static::$classes[$type];
        return new $class();
    }
}

Then you can add car types during runtime.

CarFactory::$classes['foo'] = 'FooClass';
$foo = CarFactory::create('foo');
y o
  • 1,143
  • 9
  • 14