FACTORY METHOD PATTERN
12 June 2025 20:29
The Factory Method Pattern is a creational design pattern that provides an
interface for creating objects in a superclass, but allows subclasses to alter the
type of objects that will be created.
Definition:
Define an interface for creating an object, but let subclasses decide which
class to instantiate. Factory Method lets a class defer instantiation to
subclasses.
✅ When to Use:
• When the exact type of the object to be created isn't known
until runtime.
• When you want to delegate the instantiation logic to subclasses.
• When you want to decouple object creation from its usage.
Java Example:
// Product interface
interface Shape {
void draw();
}
// Concrete Products
class Circle implements Shape {
public void draw() {
[Link]("Drawing Circle");
}
}
class Square implements Shape {
public void draw() {
[Link]("Drawing Square");
}
}
// Creator
abstract class ShapeFactory {
public abstract Shape createShape();
}
// Concrete Creators
Quick Notes Page 1
// Concrete Creators
class CircleFactory extends ShapeFactory {
public Shape createShape() {
return new Circle();
}
}
class SquareFactory extends ShapeFactory {
public Shape createShape() {
return new Square();
}
}
// Client
public class Main {
public static void main(String[] args) {
ShapeFactory factory = new CircleFactory();
Shape shape = [Link]();
[Link](); // Output: Drawing Circle
factory = new SquareFactory();
shape = [Link]();
[Link](); // Output: Drawing Square
}
}
Quick Notes Page 2