Factory method Design Pattern
Last Updated :
14 Oct, 2024
The Factory Method Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass, allowing subclasses to alter the type of objects that will be created. This pattern is particularly useful when the exact types of objects to be created may vary or need to be determined at runtime, enabling flexibility and extensibility in object creation.

What is the Factory Method Design Pattern?
The Factory Method Design Pattern is a creational design pattern used in software development. It provides an interface for creating objects in a superclass while allowing subclasses to specify the types of objects they create.
- This pattern simplifies the object creation process by placing it in a dedicated method, promoting loose coupling between the object creator and the objects themselves.
- This approach enhances flexibility, extensibility, and maintainability, enabling subclasses to implement their own factory methods for creating specific object types.
When to Use the Factory Method Design Pattern
Below is when to use factory method design pattern:
- If your object creation process is complex or varies under different conditions, using a factory method can make your client code simpler and promote reusability.
- The Factory Method Pattern allows you to create objects through an interface or abstract class, hiding the details of concrete implementations. This reduces dependencies and makes it easier to modify or expand the system without affecting existing code.
- If your application needs to create different versions of a product or may introduce new types in the future, the Factory Method Pattern provides a flexible way to handle these variations by defining specific factory methods for each product type.
- Factories can also encapsulate configuration logic, allowing clients to customize the object creation process by providing parameters or options to the factory method.
Components of Factory Method Design Pattern
Below are the main components of Factory Design Pattern:
- Creator: This is an abstract class or an interface that declares the factory method. The creator typically contains a method that serves as a factory for creating objects. It may also contain other methods that work with the created objects.
- Concrete Creator: Concrete Creator classes are subclasses of the Creator that implement the factory method to create specific types of objects. Each Concrete Creator is responsible for creating a particular product.
- Product: This is the interface or abstract class for the objects that the factory method creates. The Product defines the common interface for all objects that the factory method can create.
- Concrete Product: Concrete Product classes are the actual objects that the factory method creates. Each Concrete Product class implements the Product interface or extends the Product abstract class.
Factory Method Design Pattern Example
Below is the problem statement to understand Factory Method Design Pattern:
Consider a software application that needs to handle the creation of various types of vehicles, such as Two Wheelers, Three Wheelers, and Four Wheelers. Each type of vehicle has its own specific properties and behaviors.
1. Without Factory Method Design Pattern
Java
/*package whatever //do not write package name here */
import java.io.*;
// Library classes
abstract class Vehicle {
public abstract void printVehicle();
}
class TwoWheeler extends Vehicle {
public void printVehicle() {
System.out.println("I am two wheeler");
}
}
class FourWheeler extends Vehicle {
public void printVehicle() {
System.out.println("I am four wheeler");
}
}
// Client (or user) class
class Client {
private Vehicle pVehicle;
public Client(int type) {
if (type == 1) {
pVehicle = new TwoWheeler();
} else if (type == 2) {
pVehicle = new FourWheeler();
} else {
pVehicle = null;
}
}
public void cleanup() {
if (pVehicle != null) {
pVehicle = null;
}
}
public Vehicle getVehicle() {
return pVehicle;
}
}
// Driver program
public class GFG {
public static void main(String[] args) {
Client pClient = new Client(1);
Vehicle pVehicle = pClient.getVehicle();
if (pVehicle != null) {
pVehicle.printVehicle();
}
pClient.cleanup();
}
}
Output
Issues with the Current Design
- The
Client
class creates TwoWheeler
and FourWheeler
objects directly based on input. This strong dependency makes the code hard to maintain or update. - The
Client
class not only decides which vehicle to create but also handles its lifecycle. This mixes responsibilities, which goes against the principle that a class should only have one reason to change. - To add a new vehicle type, you must modify the
Client
class, which makes it difficult to scale the design. This conflicts with the idea that classes should be open for extension but closed for modification.
Solutions to the Problems
- Define a Factory Interface: Create an interface,
VehicleFactory
, with a method to produce vehicles. - Create Specific Factories: Implement classes like
TwoWheelerFactory
and FourWheelerFactory
that follow the VehicleFactory
interface, providing methods for each vehicle type. - Revise the Client Class: Change the
Client
class to use a VehicleFactory
instance instead of creating vehicles directly. This way, it can request vehicles without using conditional logic. - Enhance Flexibility: This structure allows for easy addition of new vehicle types by simply creating new factory classes, without needing to alter existing
Client
code.
2. With Factory Method Design Pattern
Let's breakdown the code into component wise code:

1. Product Interface
Java
// Product interface representing a vehicle
public abstract class Vehicle {
public abstract void printVehicle();
}
2. Concrete Products
Java
// Concrete product classes representing different types of vehicles
public class TwoWheeler extends Vehicle {
public void printVehicle() {
System.out.println("I am two wheeler");
}
}
public class FourWheeler extends Vehicle {
public void printVehicle() {
System.out.println("I am four wheeler");
}
}
3. Creator Interface (Factory Interface)
Java
// Factory interface defining the factory method
public interface VehicleFactory {
Vehicle createVehicle();
}
4. Concrete Creators (Concrete Factories)
Java
// Concrete factory class for TwoWheeler
public class TwoWheelerFactory implements VehicleFactory {
public Vehicle createVehicle() {
return new TwoWheeler();
}
}
// Concrete factory class for FourWheeler
public class FourWheelerFactory implements VehicleFactory {
public Vehicle createVehicle() {
return new FourWheeler();
}
}
Complete Code of this example:
Java
// Library classes
abstract class Vehicle {
public abstract void printVehicle();
}
class TwoWheeler extends Vehicle {
public void printVehicle() {
System.out.println("I am two wheeler");
}
}
class FourWheeler extends Vehicle {
public void printVehicle() {
System.out.println("I am four wheeler");
}
}
// Factory Interface
interface VehicleFactory {
Vehicle createVehicle();
}
// Concrete Factory for TwoWheeler
class TwoWheelerFactory implements VehicleFactory {
public Vehicle createVehicle() {
return new TwoWheeler();
}
}
// Concrete Factory for FourWheeler
class FourWheelerFactory implements VehicleFactory {
public Vehicle createVehicle() {
return new FourWheeler();
}
}
// Client class
class Client {
private Vehicle pVehicle;
public Client(VehicleFactory factory) {
pVehicle = factory.createVehicle();
}
public Vehicle getVehicle() {
return pVehicle;
}
}
// Driver program
public class GFG {
public static void main(String[] args) {
VehicleFactory twoWheelerFactory = new TwoWheelerFactory();
Client twoWheelerClient = new Client(twoWheelerFactory);
Vehicle twoWheeler = twoWheelerClient.getVehicle();
twoWheeler.printVehicle();
VehicleFactory fourWheelerFactory = new FourWheelerFactory();
Client fourWheelerClient = new Client(fourWheelerFactory);
Vehicle fourWheeler = fourWheelerClient.getVehicle();
fourWheeler.printVehicle();
}
}
Output
I am two wheeler
I am four wheeler
In the above code:
Vehicle
serves as the Product interface, defining the common method printVehicle()
that all concrete products must implement.TwoWheeler
and FourWheeler
are concrete product classes representing different types of vehicles, implementing the printVehicle()
method.VehicleFactory
acts as the Creator interface (Factory Interface) with a method createVehicle()
representing the factory method.TwoWheelerFactory
and FourWheelerFactory
are concrete creator classes (Concrete Factories) implementing the VehicleFactory
interface to create instances of specific types of vehicles.
Use Cases of the Factory Method
Below are the main use cases of factory method design pattern:
- Used in JDBC for creating connections and in frameworks like Spring for managing beans.
- Libraries like Swing and JavaFX use factories to create flexible UI components.
- Tools like Log4j rely on factories to create configurable loggers.
- Factories help create objects from serialized data, supporting various formats.
Advantages of the Factory Method
Below are the main advantages of factory method design pattern:
- Separates creation logic from client code, improving flexibility.
- New product types can be added easily.
- Simplifies unit testing by allowing mock product creation.
- Centralizes object creation logic across the application.
- Hides specific product classes from clients, reducing dependency.
Disadvantages of the Factory Method
Below are the main advantages of factory method design pattern:
- Adds more classes and interfaces, which can complicate maintenance.
- Slight performance impacts due to polymorphism.
- Concrete creators are linked to their products.
- Clients need knowledge of specific subclasses.
- May lead to unnecessary complexity if applied too broadly.
- Factory logic can be harder to test.
Similar Reads
Software Design Patterns Tutorial Software design patterns are important tools developers, providing proven solutions to common problems encountered during software development. This article will act as tutorial to help you understand the concept of design patterns. Developers can create more robust, maintainable, and scalable softw
9 min read
Complete Guide to Design Patterns Design patterns help in addressing the recurring issues in software design and provide a shared vocabulary for developers to communicate and collaborate effectively. They have been documented and refined over time by experienced developers and software architects. Important Topics for Guide to Desig
11 min read
Types of Software Design Patterns Designing object-oriented software is hard, and designing reusable object-oriented software is even harder. Christopher Alexander says, "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way th
9 min read
1. Creational Design Patterns
Creational Design Patterns Creational Design Patterns focus on the process of object creation or problems related to object creation. They help in making a system independent of how its objects are created, composed, and represented. Creational patterns give a lot of flexibility in what gets created, who creates it, and how i
4 min read
Types of Creational Patterns
2. Structural Design Patterns
Structural Design Patterns Structural Design Patterns are solutions in software design that focus on how classes and objects are organized to form larger, functional structures. These patterns help developers simplify relationships between objects, making code more efficient, flexible, and easy to maintain. By using structura
7 min read
Types of Structural Patterns
Adapter Design PatternOne structural design pattern that enables the usage of an existing class's interface as an additional interface is the adapter design pattern. To make two incompatible interfaces function together, it serves as a bridge. This pattern involves a single class, the adapter, responsible for joining fun
8 min read
Bridge Design PatternThe Bridge design pattern allows you to separate the abstraction from the implementation. It is a structural design pattern. There are 2 parts in Bridge design pattern : AbstractionImplementationThis is a design mechanism that encapsulates an implementation class inside of an interface class. The br
4 min read
Composite Method | Software Design PatternComposite Pattern is a structural design pattern that allows you to compose objects into tree structures to represent part-whole hierarchies. The main idea behind the Composite Pattern is to build a tree structure of objects, where individual objects and composite objects share a common interface. T
9 min read
Decorator Design PatternThe Decorator Design Pattern is a structural design pattern that allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class. It involves creating a set of decorator classes that are used to wrap concrete components.Important Top
9 min read
Facade Method Design PatternFacade Method Design Pattern is a part of the Gang of Four design patterns and it is categorized under Structural design patterns. Before we go into the details, visualize a structure. The house is the facade, it is visible to the outside world, but beneath it is a working system of pipes, cables, a
8 min read
Flyweight Design PatternThe Flyweight design pattern is a structural pattern that optimizes memory usage by sharing a common state among multiple objects. It aims to reduce the number of objects created and to decrease memory footprint, which is particularly useful when dealing with a large number of similar objects.Flywei
10 min read
Proxy Design PatternThe Proxy Design Pattern a structural design pattern is a way to use a placeholder object to control access to another object. Instead of interacting directly with the main object, the client talks to the proxy, which then manages the interaction. This is useful for things like controlling access, d
9 min read
3. Behvioural Design Patterns