Factory Method
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
The Problem
Your framework needs to create objects, but it should not be hardcoded to specific classes. The framework knows when to create, but not what to create. Subclasses or configurations should control what gets built.
Structure
Execution Walkthrough
Product interface
Define a Product interface (e.g. Lexer) that all concrete products must implement.
Creator declares
Subclass overrides
Client uses Creator
Open/Closed
Code Comparison
Full C++ Implementation
Participants
Where it is used
Compiler front-ends
A parser factory creates Lexer, Parser, or ASTBuilder depending on the input language dialect.
LLVM
IRBuilder::Create* are factory methods producing typed IR instruction nodes for the current basic block.
Database drivers
DriverManager::getConnection() returns MySQLConnection or PostgresConnection based on the JDBC URL.
UI toolkits
Cross-platform widget factory creates WinButton on Windows and GTKButton on Linux — same call site.