Understanding Singleton Design Pattern
Understanding Singleton Design Pattern
com/design-pattern
Design Pattern
Welcome To Design Pattern Blog By Nitesh Synergy
1. Creational Patterns
(Object creation)
Used when object creation is complex or needs to be
controlled.
1 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
Appearance PatteEdit
Add new rn this
Nam e
post Purpose Nitesh Synergy
Abstract
Factory of related factories.
Factory
1. Singleton Pattern
2 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
🔹 Project: E-commerce
Application
• Singleton Use:
◦ A Logger class logs order activity, errors,
payments.
◦ DatabaseConnector class manages connections to
the MySQL DB.
◦ AppConfig class loads settings like tax %,
currencies, and uses it across services.
1. Private Constructor
Ensure the class constructor is private to prevent
instantiation from outside the class.
4. Thread Safety
3 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
5. Prevent Cloning
Override the cloning behavior to avoid duplication of the
singleton object via clone() .
6. Serialization Safety
Implement mechanisms (like readResolve() in Java) to prevent
deserialization from creating a new instance.
7. Reflection Safety
Add checks inside the constructor to throw an exception if an
instance already exists, thus protecting against reflection-
based instantiation.
4 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
private Singleton() {
// Private constructor
}
Sol-2:
Lazy Initialization
• Advantages: Instance is created only when
required.
• Disadvantages: Not thread-safe.
private Singleton() {
// Private constructor
}
Sol-3:
• advantages: Thread-safe.
5 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
Appearance
• DiEdit
Add new
sadthis
vanpost
tages: Performance overhead due to Nitesh Synergy
synchronized method.
private Singleton() {
// Private constructor
}
Sol-4:
private Singleton() {
// Private constructor
}
Sol-5:
Reflection Safety:
6 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
Sol-6:
try {
// Simulating user creation logic
if (username == null ||
[Link]()) {
throw new
IllegalArgumentException("Username cannot be null
7 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
or empty");
Appearance Add new Edit this post Nitesh Synergy
}
// Simulate user created
[Link]("User created
successfully: " + username);
} catch (Exception e) {
// Log the error using Singleton Logger
[Link]("Error
creating user: " + [Link]());
}
}
}
Sol-7:
Sol-8:
8 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
private Singleton() {
Appearance Add new Edit this post Nitesh Synergy
if (instance != null) {
throw new
IllegalStateException("Singleton instance already
created!");
}
}
public static Singleton getInstance() {
if (instance == null) {
synchronized ([Link]) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
// Ensure Singleton instance is preserved
during serialization/deserialization
protected Object readResolve() {
return instance;
}
}
Sol-9:
9 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
}
Appearance Add new Edit this post Nitesh Synergy
Sol-10:
[Link]([Link]());
[Link]([Link]());
} catch (Exception e) {
[Link]();
}
}
}
10 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
[Link]([Link]());
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
[Link](" From
11 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
BreakWithMultithreading");
Appearance Add new Edit this post Nitesh Synergy
[Link]();
[Link]();
}
}
//6. Subclassing
class BreakWithSubclassing {
public static void breakWithSubclassing() {
// Singleton subclassInstance = new
Singleton() {}; // Anonymous subclass
//
[Link]([Link]());
}
}
class Singleton{
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
12 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
}
Appearance Add new Edit this post Nitesh Synergy
package
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Demo1 {
public static void main(String[] args) throws
Exception {
/* Singleton s1 = [Link]();
[Link]([Link]());
Singleton s2 = [Link]();
[Link]([Link]());
*/
[Link]();
[Link]();
[Link]();
[Link]();
[Link]
ion();
[Link]();
}
//Prevention Strategies:
//Prevent Reflection: Add a check in the
private constructor.
/* private Singleton() {
if (instance != null) {
throw new
IllegalStateException("Instance already
created!");
}
}*/
//Serialization Protection: Implement
readResolve().
/* protected Object readResolve() {
return instance;
}*/
//Prevent Cloning: Override clone() and throw
an exception.
//java
13 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
//Copy code
Appearance Add new Edit this post Nitesh Synergy
@Override
protected Object clone() throws
CloneNotSupportedException {
throw new
CloneNotSupportedException("Cannot clone
singleton");
}
//Thread-Safe Initialization: Use Bill Pugh
Singleton or Double-Checked Locking.
//Final Class: Declare the class as final to
prevent subclassing.
🔹 Why Singleton?
🔹 Why Singleton?
🎮 3. Gaming Application
Use Case: GameSettings or GameEngine Singleton
14 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
Appearance
• InEdit
Add new
a this
game,
post
GameSettings (like resolution, sound Nitesh Synergy
level, difficulty level) are set once and used
across multiple levels/screens.
• Or the GameEngine managing game loop, rendering,
and physics should only be one across the app.
🔹 Why Singleton?
🔹 Why Singleton?
📌 Summary Table
Maintain
Banking TransactionManager consistency and
log transactions
Reuse DB
JDBC/ connections,
DatabaseConnectionManager
Backend optimize
resource usage
Global settings
Gaming GameEngine / GameSettings and logic across
game screens
Centralized
AI AIModelManager /
model config and
Tools APIClient
API management
15 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
import [Link];
private GameEngineSingleton() {
if ([Link] != null) {
throw new IllegalStateException("Instance already
created!");
}
}
@Override
protected Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException("Cloning not
allowed for GameEngineSingleton");
}
// Game-related logic
public void startGame() {
[Link]("Game started...");
}
✅ [Link] — Client
Code to Use Singleton
package [Link];
16 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
GameEngineSingleton engine2 =
Appearance Add new Edit this post Nitesh Synergy
[Link]();
[Link]();
[Link]();
Reason Explanation
→ Next
Factory Pattern
17 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
🎯 Use Cases
• UI Components (Buttons, Windows, Themes)
• Payment Gateways (CreditCard, PayPal, UPI)
• Notification Systems (Email, SMS, Push)
• Gaming Characters (Player, Enemy, NPCs)
• Vehicle Production (Car, Bike, Truck)
→ Common Interface:
public interface GameCharacter {
void action();
}
Implementations:
18 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
Factory Class :
Client Code:
[Link]();
[Link]();
[Link]();
}
}
✅Why Factory is
Ideal Here
With Factory
Aspect Without Factory
Pattern
Centralized in
Object Scattered in
one factory
Creation multiple places
class
Just extend
Adding New
Modify client code factory + new
Character
class
Handled
Manually handled
Polymorphism elegantly via
or inconsistent
interface
19 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
Appearance Add new Edit this post With Factory Nitesh Synergy
Aspect Without Factory
Pattern
Harder due to
Testing and Easy to mock via
direct
Mocking interface
instantiation
Prototype Pattern
Use Case
• Games: Creating characters, weapons, or other
entities with shared configurations.
• Document Processing: Cloning complex document
templates.
• GUI Applications: Reproducing UI elements like
buttons and windows.
• Simulations: Copying complex objects like vehicles
or terrain.
20 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
@Override
Appearance Add new Edit this post Nitesh Synergy
public Prototype clone() {
return new Circle([Link]);
}
@Override
public String toString() {
return "Circle with radius " + radius;
}
}
@Override
public Prototype clone() {
return new Rectangle([Link],
[Link]);
}
@Override
public String toString() {
return "Rectangle [width=" + width + ",
height=" + height + "]";
}
}
import [Link];
import [Link];
21 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
// Register prototypes
PrototypeRegistry registry = new
PrototypeRegistry();
[Link]("circle",
circlePrototype);
[Link]("rectangle",
rectanglePrototype);
// Modify clones
[Link](15);
[Link](40, 50);
// Print results
[Link](clonedCircle); //
Circle with radius 15
[Link](clonedRectangle); //
Rectangle [width=40, height=50]
}
}
22 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
@Override
public GameEntity clone() {
return new Player([Link], [Link],
[Link]);
}
@Override
public void render() {
[Link]("Player: " + name + ",
Health: " + health + ", Attack Power: " +
attackPower);
}
}
23 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
[Link] = health;
Appearance Add new Edit this post Nitesh Synergy
}
@Override
public GameEntity clone() {
return new Enemy([Link], [Link]);
}
@Override
public void render() {
[Link]("Enemy: " + type + ",
Health: " + health);
}
}
import [Link];
import [Link];
// Register prototypes
GameEntityRegistry registry = new
GameEntityRegistry();
[Link]("player",
playerPrototype);
[Link]("zombie",
enemyPrototype);
24 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
// Render entities
[Link]();
[Link]();
}
}
Output Example
Builder Pattern
🔍 Real-life Analogy:
Imagine building a burger at a restaurant:
You choose bun, cheese, veggies, sauces, etc.
The Burger Builder prepares it step-by-step.
You get the final burger your way 🍔
Use Case
1. Constructing objects with many optional
parameters, such as HTTP requests.
2. Building vehicles in games, e.g., tanks, cars, and
planes.
3. Assembling complex entities in RPG games, e.g.,
player profiles or NPCs.
25 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
@Override
public void buildFoundation() {
[Link]("Wooden Foundation");
}
@Override
public void buildStructure() {
[Link]("Wooden Structure");
}
@Override
public void buildRoof() {
[Link]("Wooden Roof");
}
@Override
public House getHouse() {
return house;
}
}
26 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
@Override
public void buildFoundation() {
[Link]("Stone Foundation");
}
@Override
public void buildStructure() {
[Link]("Stone Structure");
}
@Override
public void buildRoof() {
[Link]("Stone Roof");
}
@Override
public House getHouse() {
return house;
}
}
Step 4: Director
27 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
Output Example
House [Foundation=Wooden Foundation,
Structure=Wooden Structure, Roof=Wooden Roof]
House [Foundation=Stone Foundation,
Structure=Stone Structure, Roof=Stone Roof]
• 🔍 Real-life Analogy:
• Imagine a Furniture Factory:
Use Case
1. Cross-platform UI: Creating compatible widgets
like buttons and checkboxes for Windows, Mac, and
Linux.
2. Gaming: Creating characters, weapons, and armor
28 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
🏦 Scenario:
You want to create banking-related objects: Loan and Account.
Depending on the Bank (e.g., HDFC or SBI), the system should
return the corresponding Account and Loan.
interface Account {
void accountType();
}
interface Loan {
void loanType();
}
interface BankFactory {
Account createAccount();
Loan createLoan();
}
29 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
class BankFactoryProvider {
public static BankFactory getBankFactory(String bank) {
return switch ([Link]()) {
case "hdfc" -> new HDFCBankFactory();
case "sbi" -> new SBIBankFactory();
default -> throw new
IllegalArgumentException("Unknown bank");
};
}
}
Create Create
Clone Ensure on
objects via related Build complex object
Purpose existing instance
subclass or families of step-by-step
object app
method objects
30 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
Appearance FeatuEdit
Add new re this
/ postFactory Abstract Nitesh Synergy
Builder Prototype Singleton
Pattern Method Factory
Cloning
Object Uses method/ Uses factory Step-wise Lazy or e
existing
Creation logic for families construction initializ
object
Client ❌ No (dir
✅ Knows
Knows ❌ No ❌ No ✅ Yes (via builder) access vi
prototype
Concrete? static me
App-wide
Vary object Vary product Complex object (many Duplicate
When to config/
by input/ family across configs, configured
Use resource
context app immutability) object
manager
GameUIFactory
Clone GameSetti
Key EnemyFactory → MacOS/
GameCharacterBuilder Enemy (volume,
Example → creates Windows
→ Hero with weapons object with level, us
(Game) Orc/Zombie buttons,
new HP ID)
menus
Many
Class Hidden
interfaces, Shallow vs.
Main explosion Verbose if simple dependenc
can be deep copy
Drawback (many objects threading
abstract- issues
factories) issues
heavy
Furniture
Pizza shop factory
Real-World Meal builder (choose Copying a Governmen
with types (Modern/
Analogy base, sides, drink) filled form system
(Veg/Non-Veg) Victorian
sets)
31 of 32 07/11/25, 10:12 pm
Design Pattern [Link]
Structural Design
Pattern
Adapter Pattern:
23 min read
By Nitesh Synergy
SHARE
32 of 32 07/11/25, 10:12 pm