Overview
The Factory Method Design Pattern provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. It promotes loose coupling by delegating the instantiation logic to subclasses.
Key Characteristics
- Defines an interface for creating objects.
- Delegates the responsibility of instantiating objects to subclasses.
- Promotes the Open/Closed Principle by allowing new types to be added without modifying existing code.
Implementation
The following is an example of a Factory Method implementation in Java:
abstract class Product {
abstract void use();
}
class ConcreteProductA extends Product {
@Override
void use() {
System.out.println("Using Product A");
}
}
class ConcreteProductB extends Product {
@Override
void use() {
System.out.println("Using Product B");
}
}
abstract class Creator {
abstract Product createProduct();
}
class ConcreteCreatorA extends Creator {
@Override
Product createProduct() {
return new ConcreteProductA();
}
}
class ConcreteCreatorB extends Creator {
@Override
Product createProduct() {
return new ConcreteProductB();
}
}
When to Use
- When a class cannot anticipate the type of objects it needs to create.
- When a class wants its subclasses to specify the objects it creates.
Advantages
- Promotes loose coupling between client code and concrete classes.
- Makes the code more scalable and adheres to the Open/Closed Principle.
Disadvantages
- Can result in a more complex code structure due to additional classes.