Factory Design Pattern

The Factory Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. It encapsulates the object creation logic, providing flexibility and decoupling between the client code and the created objects. Let’s explain the Factory pattern with an example in PHP:

// Interface for product classes
interface Vehicle {
    public function drive();
}

// Concrete product classes
class Car implements Vehicle {
    public function drive() {
        return "Driving a car...";
    }
}

class Truck implements Vehicle {
    public function drive() {
        return "Driving a truck...";
    }
}

// Factory class
class VehicleFactory {
    public static function createVehicle($type) {
        switch ($type) {
            case 'car':
                return new Car();
            case 'truck':
                return new Truck();
            default:
                throw new InvalidArgumentException("Invalid vehicle type specified.");
        }
    }
}

// Client code
$car = VehicleFactory::createVehicle('car');
echo $car->drive(); // Output: Driving a car...

$truck = VehicleFactory::createVehicle('truck');
echo $truck->drive(); // Output: Driving a truck...

Explanation:

  • We define an interface Vehicle that declares a method drive(), which all concrete product classes (e.g., Car and Truck) will implement.
  • Concrete product classes (Car and Truck) implement the Vehicle interface and provide their own implementation of the drive() method.
  • The VehicleFactory class serves as the factory for creating instances of different vehicle types based on the input parameter.
  • The createVehicle() method in the factory class switches on the input parameter and instantiates the appropriate type of vehicle object (Car or Truck).
  • Client code uses the factory method createVehicle() to create instances of vehicles without needing to know the specific class implementations.

Why do we need to use the Factory Design Pattern?

  1. Encapsulation of Object Creation: The Factory pattern encapsulates the creation logic, abstracting it from the client code. This allows for centralized management of object creation and modification without affecting client code.
  2. Flexibility and Extensibility: Factory methods allow for easy extension by adding new product classes or modifying existing ones without changing the client code. This promotes code flexibility and modifiability.
  3. Decoupling: The Factory pattern decouples the client code from the concrete implementations of objects. Clients rely on interfaces and factory methods, rather than concrete classes, reducing dependencies and making the codebase more maintainable.
  4. Consistency: Factories ensure consistent object creation throughout the application, enforcing common creation logic and reducing code duplication.

Overall, the Factory Design Pattern promotes code reusability, flexibility, and maintainability by encapsulating object creation logic and providing a centralized mechanism for creating objects. It’s particularly useful in scenarios where object creation is complex or likely to change over time.

Remove Static Keyword in Above Code Example :

To remove the static keyword from the createVehicle() method and create an instance of the VehicleFactory class to call the method, you can modify the code as follows:

<?php

// Interface for product classes
interface Vehicle {
    public function drive();
}

// Concrete product classes
class Car implements Vehicle {
    public function drive() {
        return "Driving a car...";
    }
}

class Truck implements Vehicle {
    public function drive() {
        return "Driving a truck...";
    }
}

// Factory class
class VehicleFactory {
    public function createVehicle($type) {
        switch ($type) {
            case 'car':
                return new Car();
            case 'truck':
                return new Truck();
            default:
                throw new InvalidArgumentException("Invalid vehicle type specified.");
        }
    }
}

// Client code
$factory = new VehicleFactory();

$car = $factory->createVehicle('car');
echo $car->drive(); // Output: Driving a car...

$truck = $factory->createVehicle('truck');
echo $truck->drive(); // Output: Driving a truck...

?>

In this modified code:

  • The createVehicle() method in the VehicleFactory class is no longer static.
  • We create an instance of the VehicleFactory class using $factory = new VehicleFactory();.
  • We call the createVehicle() method on the $factory object to create instances of Car or Truck based on the input parameter.

Related Posts

Leave A Comment