Definition
“Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes”
Explanation
You define an abstract factory interface (e.g.,GUIFactory) with methods to create various related products (e.g.
createButton(), createCheckbox()). Concrete factories (WindowsFactory, MacFactory) implement these methods to produce
OS-specific components. Client code uses the abstract factory interface to create components, so it stays agnostic of
concrete classes. This ensures products from the same family are used together.
Code
The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. In this code, AbstractFactory declares methods for creating abstract products A and B. ConcreteFactory1 and ConcreteFactory2 produce corresponding concrete products (ConcreteProductA1/A2, ConcreteProductB1/B2). The client_code function works with factories to produce products and invoke their methods.Analogy
Think of a furniture showroom: you pick a modern or Victorian style, which is an abstract factory. All furniture you get (chairs, tables, sofas) will match that style. If you choose “Victorian”, the Victorian factory gives you Victorian chairs/tables. Client code just asks for createChair(), createTable() on the selected factory and gets matching items, with no knowledge of concrete styles.Interview Insights
Common uses: When a system needs to be independent of how its products are created. Useful for cross-platform UI widgets (ensuring all controls belong to same theme), or when swapping entire product families (e.g. dark vs light theme packs). Often used with Factory Methods to get factories.Advantages: Enforces consistency among related products. Decouples concrete product classes from client. Easy to switch entire families of products by plugging a different factory.
Disadvantages: Hard to add new product types (methods on factory interface must be added, all factories updated). Many classes (one factory per family). Can be overkill if you only need one product type.\