Overview
The Abstract Factory Design Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is often used when the system needs to create multiple families of products.
Key Characteristics
- Encapsulates a group of individual factories with a common interface.
- Promotes consistency among products of the same family.
- Adheres to the Open/Closed Principle by allowing new families of products to be added without modifying existing code.
Implementation
The following is an example of an Abstract Factory implementation in Java:
// Abstract product interfaces
interface Chair {
void sitOn();
}
interface Table {
void use();
}
// Concrete products
class ModernChair implements Chair {
@Override
public void sitOn() {
System.out.println("Sitting on a modern chair.");
}
}
class VictorianChair implements Chair {
@Override
public void sitOn() {
System.out.println("Sitting on a Victorian chair.");
}
}
class ModernTable implements Table {
@Override
public void use() {
System.out.println("Using a modern table.");
}
}
class VictorianTable implements Table {
@Override
public void use() {
System.out.println("Using a Victorian table.");
}
}
// Abstract factory
interface FurnitureFactory {
Chair createChair();
Table createTable();
}
// Concrete factories
class ModernFurnitureFactory implements FurnitureFactory {
@Override
public Chair createChair() {
return new ModernChair();
}
@Override
public Table createTable() {
return new ModernTable();
}
}
class VictorianFurnitureFactory implements FurnitureFactory {
@Override
public Chair createChair() {
return new VictorianChair();
}
@Override
public Table createTable() {
return new VictorianTable();
}
}
When to Use
- When a system needs to create families of related objects.
- When products need to ensure consistency across related objects.
Advantages
- Promotes consistency among objects within a family.
- Adheres to the Open/Closed Principle by allowing easy addition of new families.
Disadvantages
- Adding new product families requires changes to the abstract factory interface and all concrete factories.
- Can increase complexity due to the introduction of multiple factories and products.