0% found this document useful (0 votes)
4 views

Singleton Pattern

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Singleton Pattern

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Singleton Pattern

Student’s name: Luong Linh Khoi


Student’s ID: 23127396

Introduction
The Singleton Pattern a Creational design pattern, which ensures
that only one object of its kind exists and provides a single point
of access to it for any other code.

Applicability
Use the Singleton pattern when
 there must be exactly one instance of a class, and it must be
accessible to clients from a well-known access point.
 when the sole instance should be extensible by subclassing,
and clients should be able to use an extended instance
without modifying their code.

Participants
 Singleton
- defines an getInstance operation that lets clients access its
unique instance. getInstance is a class operation
- may be responsible for creating its own unique instance

Consequences
 You can be sure that a class has only a single instance.
 You gain a global access point to that instance.
 The singleton object is initialized only when it’s requested for
the first time.
 Violates the Single Responsibility Principle. Because they are
responsible for enforcing their own uniqueness along with
performing their normal functions
 It introduces a potential dependency on the singleton by
other objects, requiring analysis of implementation details to
determine whether a dependency actually exists  increases
coupling and introduces difficulties with unit testing

Use cases
 Logging Systems: A globally accessible logging system
that all parts of the application can use without creating
multiple logger instances.
 Configuration Management: Centralized storage for
application-wide settings;
 Resource Management: Managing global resources such
as device drivers, file systems, or network connections.

UML Diagram

Pseudocode
// Singleton Class
class Singleton:
// Static variable to hold the single instance
private static instance: Singleton = null

// Private constructor to prevent instantiation


private Singleton():
// Initialization code here
// Static method to get the single instance
static method getInstance(): Singleton:
if instance == null:
instance = new Singleton()
return instance

References
[1] Wikipedia, Singleton pattern,
https://en.wikipedia.org/wiki/Singleton_pattern
[2] Refactoring Guru, Singleton, https://refactoring.guru/design-
patterns/singleton
[3] Design Patterns Elements of Reusable Object-Oriented
Software, Erich Gamma, Richard Helm, Ralph Johnson, John M.
Vlissides

You might also like