The Wayback Machine - https://web.archive.org/web/20240718222210/https://www.geeksforgeeks.org/difference-between-singleton-and-factory-design-pattern-in-java/
Open In App

Difference Between Singleton and Factory Design Pattern in Java

Last Updated : 27 Nov, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Design patterns are essential tools for creating maintainable and scalable software. Two commonly used design patterns in Java are the Singleton and Factory patterns. This article provides an introduction to the Singleton and Factory design patterns with examples.

Singleton Design Pattern in Java

The Singleton pattern is a creational design pattern that ensures that only one instance of a class can be created and that the same instance is used every time the object is requested.

Example:

Java




import java.io.*;
  
public class Singleton {
    // Private static variable to hold the single instance
    // of the class
    private static Singleton instance = null;
  
    // Private constructor to prevent outside instantiation
    private Singleton() {}
  
    // Public static method to get the single instance of
    // the class
    public static Singleton getInstance()
    {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
  
    // Public method to demonstrate the Singleton instance
    public void showMessage()
    {
        System.out.println(
            "Hello, I am the Singleton instance.");
    }
  
    public static void main(String[] args)
    {
        // Get the Singleton instance
        Singleton singleton = Singleton.getInstance();
  
        // Call a method on the Singleton instance
        singleton.showMessage();
    }
}


Output:

Hello, I am the Singleton instance.

Factory Design Pattern in Java

The Factory pattern is a creational pattern that provides a way to create objects without specifying the exact class of object that will be created. It provides a factory method that is responsible for creating objects of the appropriate type based on a set of criteria, such as a type or a configuration parameter.

Example:

Java




import java.io.*;
  
interface Shape {
    void draw();
}
  
class Rectangle implements Shape {
    public void draw()
    {
        System.out.println("Drawing a rectangle.");
    }
}
  
class Circle implements Shape {
    public void draw()
    {
        System.out.println("Drawing a circle.");
    }
}
  
class ShapeFactory {
    // Factory method to create Shape objects based on the
    // input String
    public Shape getShape(String shapeType)
    {
        if (shapeType == null) {
            return null;
        }
        else if (shapeType.equalsIgnoreCase("rectangle")) {
            return new Rectangle();
        }
        else if (shapeType.equalsIgnoreCase("circle")) {
            return new Circle();
        }
        return null;
    }
}
  
public class FactoryPatternExample {
    public static void main(String[] args)
    {
        // Create a ShapeFactory object
        ShapeFactory shapeFactory = new ShapeFactory();
  
        // Get a Rectangle object and call its draw method
        Shape shape1 = shapeFactory.getShape("rectangle");
        shape1.draw();
  
        // Get a Circle object and call its draw method
        Shape shape2 = shapeFactory.getShape("circle");
        shape2.draw();
    }
}


Output:

Drawing a rectangle.
Drawing a circle.

Difference Between Singleton and Factory Design Pattern in Java

Characteristics

Singleton Design Pattern

Factory Design Pattern

Purpose

Ensures a single instance of class and provides global access

Creates the objects without exposing the creation logic

Number of Instances

Only one instance per class

The Multiple instances can be created as needed

Construction

The singleton class controls its own instantiation using the method like getInstance()

A factory class or method is responsible for the object creation

Object Creation

Limited to single instance

Can create multiple instances with the different configurations

Example

java.lang.Runtime Spring’s ApplicationContext

java.util.Calendar javax.xml.parsers.DocumentBuilderFactory

Usage Scenario

When you need exactly one instance to manage the shared resources or settings

When you want to centralize object creation and decouple code



Similar Reads

Difference Between Singleton Pattern and Static Class in Java
Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object o
6 min read
Singleton Method Design Pattern in Java
In object-oriented programming, a java singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Java Singleton classes, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any inst
8 min read
Java Singleton Design Pattern Practices with Examples
In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your requirement, which is simple and without bottlenecks. There are many ways this
6 min read
Singleton Design Pattern in Java
Singleton Design Pattern is a creational design pattern that ensures a class has only one instance and provides a global point of access to it. This pattern is particularly useful when exactly one object is needed to coordinate actions across the system. Important Topics for Singleton Method in Java Problem Statement for Singleton Method:Use Case o
5 min read
Singleton Pattern | C++ Design Patterns
A singleton pattern is a design pattern that ensures that only one instance of a class can exist in the entire program. This means that if you try to create another instance of the class, it will return the same instance that was created earlier. The Singleton pattern is useful when we need to have only one instance of a class, for example, a singl
11 min read
Most asked Singleton Design Pattern Interview Questions
This article comprises some of the most asked Singleton design pattern interview questions, which will help you tackle any Singleton design pattern question properly. 1. Give an example use case for the singleton design pattern.This design pattern can be useful in various scenarios, such as when you need to control access to a shared resource, mana
11 min read
Spring - Difference Between Dependency Injection and Factory Pattern
Dependency Injection and Factory Pattern are almost similar in the sense that they both follow the interface-driven programming approach and create the instance of classes. A. Factory Pattern In Factory Pattern, the client class is still responsible for getting the instance of products by class getInstance() method of factory class, which means the
4 min read
Spring - When to Use Factory Design Pattern Instead of Dependency Injection
Prerequisite: Factory Pattern vs Dependency Injection Factory Design Pattern and Dependency Injection Design both are used to define the interface-driven programs in order to create objects. Dependency Injection is used to obtain a loosely coupled design, whereas the Factory Pattern adds coupling, between objects, factories, and dependencies. In th
2 min read
Abstract Factory Pattern | C++ Design Patterns
Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are compatible and properly configured. In this artic
6 min read
Abstract Factory Pattern | JavaScript Design Patterns
Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface to create objects. Important Topics for the Abstr
6 min read
three90RightbarBannerImg