The Abstract Factory pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It allows the client code to work with abstract interfaces, making it independent of the specific classes that implement those interfaces. Here is an example of implementing the Abstract Factory pattern in Java:
In this example, we have two families of products: ProductA and ProductB. Each product family has multiple concrete implementations (ConcreteProductA1, ConcreteProductA2, ConcreteProductB1, ConcreteProductB2).
The AbstractFactory interface declares abstract factory methods for creating ProductA and ProductB objects. The concrete factories (ConcreteFactory1 and ConcreteFactory2) implement this interface and provide concrete implementations for creating the products.
The Client class represents the client code that works with the abstract product interfaces (ProductA and ProductB) through the abstract factory interface (AbstractFactory). The client code is decoupled from the concrete product classes and factories, allowing it to work with different families of products by simply changing the concrete factory used.
In the main() method, we create instances of the concrete factories (ConcreteFactory1 and ConcreteFactory2) and pass them to the Client constructor. The Client then uses the created factories to create and work with the products (ProductA and ProductB) without being aware of their concrete classes.
The Abstract Factory pattern enables the creation of families of related products and provides an easy way to switch between different implementations of those product families.