Can you provide an example where the Factory pattern would simplify object creation?

A typical example of the Factory pattern simplifying object creation is an application that connects to multiple database types, where a factory hides which concrete connection class gets built behind a single, consistent interface.

Key Points: • A DatabaseConnectionFactory exposes a method like createConnection(String type) returning a common Connection interface. • Each database type — MySQL, PostgreSQL, Oracle — has its own concrete class implementing that interface. • Application code depends only on the interface and the factory, never on a specific vendor's connection class. • Switching or adding a supported database only requires changes inside the factory, not throughout the application. • Configuration-driven creation (e.g., reading the database type from a properties file) becomes trivial since the factory just needs a string key.

Example: Connection conn = factory.createConnection("POSTGRES") returns a PostgresConnection under the hood, but the calling code only ever interacts with it through the shared Connection interface.

Code Example:

interface DbConnection {
    void connect();
}

class MySqlConnection implements DbConnection {
    public void connect() { System.out.println("Connecting to MySQL"); }
}

class DbConnectionFactory {
    public static DbConnection create(String type) {
        if (type.equals("MYSQL")) return new MySqlConnection();
        throw new IllegalArgumentException("Unsupported: " + type);
    }
}

Interview Tip: A concise interview answer is:

"A good example is a multi-database application: instead of scattering `new MySqlConnection()` or `new PostgresConnection()` calls throughout the code, a factory exposes one createConnection(type) method that returns a common interface. That means adding support for a new database is a change in one place, the factory, not throughout the codebase."