Skip to content

Commit 901b787

Browse files
Singleton Pattern Docs
1 parent 2f02d6e commit 901b787

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

content/Singleton Pattern.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
---
2+
title: Singleton Pattern
3+
created: 2025-04-29
4+
tags:
5+
- creational
6+
---
7+
## Definition
8+
9+
The **Singleton Pattern** ensures that a class has only one instance and provides a global point of access to it.
10+
11+
---
12+
## Real-World Analogy
13+
14+
Imagine you have a database that every part of your application needs to access. Creating a new database connection each time can be expensive and requires repetitive configuration connection strings, usernames, passwords, and so on. Instead, you can use a single shared database connector that’s created once and used everywhere. This is exactly where the Singleton Pattern is useful.
15+
### Implementation in Java
16+
17+
First, create a `DatabaseConnector.java` class with a private constructor so that no one outside the class can directly create an instance. Then define a private static field to hold the single instance of the class. Provide a public static method, `getInstance()`, which returns the instance. If the instance doesn’t exist yet, it’s created; otherwise, the existing instance is returned.
18+
19+
```java title="DatabaseConnector.java"
20+
public class DatabaseConnector {
21+
// Holds the single instance
22+
private static DatabaseConnector instance;
23+
24+
private String connectionString;
25+
26+
// Private constructor prevents external instantiation
27+
private DatabaseConnector(String connectionString) {
28+
this.connectionString = connectionString;
29+
}
30+
31+
@Override
32+
public String toString() {
33+
return "DatabaseConnector[connectionString=" + connectionString + "]";
34+
}
35+
36+
// Synchronized to avoid race conditions in multithreaded environments
37+
public static synchronized DatabaseConnector getInstance() {
38+
if (instance == null) {
39+
instance = new DatabaseConnector("PostgresSQL");
40+
}
41+
return instance;
42+
}
43+
}
44+
```
45+
46+
Notice that `getInstance()` is synchronized to prevent multiple threads from creating separate instances simultaneously.
47+
48+
To use the connector:
49+
```java title="SingletonPatternExample.java"
50+
public class SingletonPatternExample {
51+
public static void main(String[] args) {
52+
DatabaseConnector conn1 = DatabaseConnector.getInstance();
53+
System.out.println(conn1);
54+
55+
DatabaseConnector conn2 = DatabaseConnector.getInstance();
56+
System.out.println(conn2);
57+
}
58+
}
59+
```
60+
61+
**Output:**
62+
```
63+
DatabaseConnector[connectionString=PostgresSQL]
64+
DatabaseConnector[connectionString=PostgresSQL]
65+
```
66+
Both calls return the same instance.
67+
68+
---
69+
## Design Diagram
70+
71+
```mermaid
72+
classDiagram
73+
class DatabaseConnector {
74+
- static DatabaseConnector instance
75+
- String connectionString
76+
- DatabaseConnector(String connectionString)
77+
+ static DatabaseConnector getInstance()
78+
+ String toString()
79+
}
80+
```
81+
82+
---
83+
## Real-World Example in Java
84+
85+
The `Runtime` class in Java also uses the Singleton Pattern. There is only one JVM per machine, so Java provides a single Runtime instance:
86+
87+
```java title="RuntimeExample.java"
88+
public class RuntimeExample {
89+
public static void main(String[] args) {
90+
Runtime rt = Runtime.getRuntime();
91+
System.out.println("Available processors: " + rt.availableProcessors());
92+
}
93+
}
94+
```
95+
96+
**Output:**
97+
```
98+
Available processors: 8
99+
```

content/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ Consider an `SQLManager` class that performs CRUD operations. It has an `ILogger
122122
3. [[Decorator Pattern]]
123123
4. [[Factory Method Pattern]]
124124
5. [[Abstract Factory Pattern]]
125+
6. [[Singleton Pattern]]
125126

126127
---
127128
> [!Note]

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy