Software

Factory Method

Factory creates objects. The clients who use the factory can focus on other behavior. So the object creation delegated to another object.

Factory Object

Benefits: if there are multiple clients that want to instantiate the same set of classes, then by using a Factory object, you have cut out redundant code and made software easier to modify. Means if need a change of object creation, then have to modify just a factory instead of every client and it’s calling coding to an interface, not an implementation.

Factory:

public class CarFactory(){
    public Car createCar(string carType) {
        Car car;
        
        if(carType.Equals("sport")){
            car = new SportCar();
        }
        else if(carType.Equals("city")){
            car = new CityCar();
        }        

        return car;
    }
}

Client:

public class CarStore {
    private CarFactory factory;

    public CarStore(CarFactory factory){
        this.factory = factory;
    }

    public Car OrderCar(string carType){
        car = factory.createCar(carType);
    
        car.validate();
        car.driveToParking();
        car.packagePreparation();

        return car;
    }
}

Although the example make loose coupling, the Factory Method can even boost flexibility.

Factory Method

The Factory Method designed intent is to define an interface for creating objects, but let the subclasses decide which class to instantiate.

Factory method (abstract):

public abstract class CarStore {
    public Car OrderCar(string carType){
        Car car;
    
        car = createCar(carType);

        car.validate();
        car.driveToParking();
        car.packagePreparation();

        return car;
    }
    
    abstract Car createCar(string carType);
}

Factory method (instantiated) which has own method to create objects:

public BudgetCarStore: CarStore {
    Car createCar(string carType){
        Car car;

        if(carType.Equals("suburb")){
            car = new SuburbCar();
        }
        else if(carType.Equals("city")){
            car = new CityCar();
        }
        //.. more types        

        return car;
    }
}
Cars Factory Method Class Diagram.png
Cars Factory Method class diagram.
Factory Method Class Diagram.png
General Factory Method class diagram.

The Factory Method comparing to the Factory Object a little bit different: instead of create objects, we separate out object creation into another method – factory method. Each subclass must define its own factory method.

One thought on “Factory Method

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.