Factory Design Pattern

This pattern is useful if we want to use another class to create objects for us. The client delegates responsibility of knowing how to create objects properly to another class, which is called the factory class. The factory class returns objects that the client is expecting.

Let’s say we have a method that all our shuttles implement:

public interface Shuttle {
    public void launch();
}

Let’s have some shuttles. Shall we?

public class Discovery implements Shuttle {
    public void launch() {
        System.out.println("Discovery is launched!");
    }
}
public class Columbia implements Shuttle {
    public void launch() {
        System.out.println("Columbia is launched!");
    }	
}

Let’s create a shuttle factory:

public class ShuttleFactory {
    public Shuttle getShuttle(String shuttle) {
        if (shuttle.equals("Columbia")) {
            return new Columbia();
        } else if (shuttle.equals("Discovery")) {
           return new Discovery();
        }
        return null;
    }
}

To create and launch a specific shuttle, just send use it’s name as an argument:

public static void main(String[] args) {
    ShuttleFactory factory = new ShuttleFactory();
    Shuttle shuttle = factory.getShuttle("Columbia");
    shuttle.launch();
}

The factory design pattern is simple, but very powerful. We also may use Enums in order to remove logic statements from the shuttle factory.