Commit 04c8e35
committed
feat: Implement Singleton design pattern with PrivateConstructor class
WHAT the code does:
- Defines a `PrivateConstructor` class that restricts object creation.
- Declares a static field `School` to hold the single instance.
- Makes the constructor `private` so no external code can instantiate the class.
- Provides `getInstance()` method:
- If `School` is `null`, creates a new instance.
- Otherwise, returns the existing instance.
- `main()` repeatedly calls `getInstance()` to demonstrate that only one object is created.
WHY this matters:
- Implements the **Singleton pattern** — ensures only one instance of a class exists.
- Useful for cases like configuration managers, logging, thread pools, or database connections.
- Demonstrates **controlled object creation** using private constructors and static methods.
HOW it works:
1. First call to `getInstance()` → `School` is null → creates new `PrivateConstructor` object.
2. Later calls return the same object reference, preventing multiple creations.
3. Program ensures all callers use the same singleton instance.
Tips & gotchas:
- This is a **lazy initialization** singleton → instance created only when needed.
- Not thread-safe: multiple threads could create multiple instances at the same time.
→ Can fix with synchronized `getInstance()` or double-checked locking.
- For strict immutability, mark the singleton instance as `final` and initialize eagerly.
- Enum-based singletons in Java are simpler and thread-safe by default.
Use-cases:
- Logger classes.
- Database connection pools.
- Application configuration objects.
- Resource managers that must be globally consistent.
Short key: pattern-singleton-private constructor.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 2334fae commit 04c8e35
1 file changed
+16
-17
lines changedLines changed: 16 additions & 17 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | | - | |
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
8 | 8 | | |
9 | 9 | | |
10 | | - | |
| 10 | + | |
11 | 11 | | |
12 | 12 | | |
13 | 13 | | |
14 | | - | |
15 | | - | |
16 | | - | |
17 | | - | |
18 | | - | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
19 | 17 | | |
20 | 18 | | |
21 | 19 | | |
22 | 20 | | |
23 | | - | |
24 | 21 | | |
25 | 22 | | |
26 | 23 | | |
| |||
29 | 26 | | |
30 | 27 | | |
31 | 28 | | |
32 | | - | |
33 | | - | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
34 | 33 | | |
35 | | - | |
| 34 | + | |
0 commit comments