Add all 23 GoF design pattern implementations

This commit is contained in:
2026-07-25 10:50:29 +05:30
commit f5688a6b32
164 changed files with 4371 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
package singleton;
public class AppConfigDCL {
// volatile is MANDATORY for DCL to work correctly.
// Without it, the JVM can reorder the writes inside the constructor
// and return a partially-constructed object to a second thread.
private static volatile AppConfigDCL instance;
private AppConfigDCL() { /* load config */ }
public static AppConfigDCL getInstance() {
// First check: no lock, instant return for the 99.99% case
// (instance already created, just return it)
if (instance == null) {
// Lock only when first check says we might need to create
synchronized (AppConfigDCL.class) {
// Second check: re-verify under the lock.
// Another thread might have created the instance between
// our first check and acquiring the lock.
if (instance == null) {
instance = new AppConfigDCL();
}
}
}
return instance;
}
}

View File

@@ -0,0 +1,24 @@
package singleton;
public class AppConfigEager {
// The JVM creates this instance when the class is first loaded.
// static guarantees it belongs to the class, not any instance.
// final guarantees it can never be reassigned.
private static final AppConfigEager INSTANCE = new AppConfigEager();
// Private constructor: prevents any other class from calling new AppConfigEager()
private AppConfigEager() {
System.out.println("Reading configuration from file...");
// load properties, set up values, etc.
}
// The only way to get the instance
public static AppConfigEager getInstance() {
return INSTANCE;
}
public String getProperty(String key) {
return System.getProperty(key, "(not set)");
}
}

View File

@@ -0,0 +1,19 @@
package singleton;
public enum AppConfigEnum {
INSTANCE; // The JVM creates this exactly once, period.
// Enum instances can have fields and methods like any class
private final String configPath;
AppConfigEnum() {
// Enum constructors run once, when the constant is first used
this.configPath = System.getProperty("config.path", "application.properties");
System.out.println("Loading config from: " + configPath);
}
public String getProperty(String key) {
return System.getProperty(key, "(not set)");
}
}

View File

@@ -0,0 +1,19 @@
package singleton;
public class AppConfigHolder {
private AppConfigHolder() { /* load config */ }
// The JVM loads Holder only when getInstance() is first called.
// Class loading is inherently thread-safe — the JVM ensures it happens once.
// No synchronized, no volatile, no locks — just the JVM class loading guarantee.
private static class Holder {
static final AppConfigHolder INSTANCE = new AppConfigHolder();
}
public static AppConfigHolder getInstance() {
// This reference triggers Holder to load (if it hasn't already).
// After first call, Holder is already loaded and this is just a field read.
return Holder.INSTANCE;
}
}

View File

@@ -0,0 +1,16 @@
package singleton;
public class AppConfigNaiveLazy {
private static AppConfigNaiveLazy instance; // null until first request
private AppConfigNaiveLazy() { /* load config */ }
// BROKEN IN MULTITHREADED CODE — see explanation below
public static AppConfigNaiveLazy getInstance() {
if (instance == null) { // Thread A: checks, sees null
instance = new AppConfigNaiveLazy(); // Thread B: also sees null, also enters here
} // Both threads create a new AppConfigNaiveLazy!
return instance;
}
}

View File

@@ -0,0 +1,16 @@
package singleton;
public class AppConfigSynchronized {
private static AppConfigSynchronized instance;
private AppConfigSynchronized() { /* load config */ }
// synchronized: only one thread can execute this method at a time
public static synchronized AppConfigSynchronized getInstance() {
if (instance == null) {
instance = new AppConfigSynchronized(); // safe — no other thread can be here
}
return instance;
}
}

View File

@@ -0,0 +1,36 @@
package singleton;
public class Main {
public static void main(String[] args) {
System.out.println("--- Implementation 1: Eager ---");
AppConfigEager eager1 = AppConfigEager.getInstance();
AppConfigEager eager2 = AppConfigEager.getInstance();
System.out.println("Same instance? " + (eager1 == eager2));
System.out.println("db.url = " + eager1.getProperty("db.url"));
System.out.println("\n--- Implementation 2: Naive Lazy ---");
AppConfigNaiveLazy lazy1 = AppConfigNaiveLazy.getInstance();
AppConfigNaiveLazy lazy2 = AppConfigNaiveLazy.getInstance();
System.out.println("Same instance? " + (lazy1 == lazy2));
System.out.println("\n--- Implementation 3: Synchronized Method ---");
AppConfigSynchronized sync1 = AppConfigSynchronized.getInstance();
AppConfigSynchronized sync2 = AppConfigSynchronized.getInstance();
System.out.println("Same instance? " + (sync1 == sync2));
System.out.println("\n--- Implementation 4: Double-Checked Locking ---");
AppConfigDCL dcl1 = AppConfigDCL.getInstance();
AppConfigDCL dcl2 = AppConfigDCL.getInstance();
System.out.println("Same instance? " + (dcl1 == dcl2));
System.out.println("\n--- Implementation 5: Holder Idiom ---");
AppConfigHolder holder1 = AppConfigHolder.getInstance();
AppConfigHolder holder2 = AppConfigHolder.getInstance();
System.out.println("Same instance? " + (holder1 == holder2));
System.out.println("\n--- Implementation 6: Enum ---");
AppConfigEnum enumConfig = AppConfigEnum.INSTANCE;
System.out.println("db.url = " + enumConfig.getProperty("db.url"));
}
}

View File

@@ -0,0 +1,34 @@
# Singleton Design Pattern — Java Example
**Pattern:** Creational → Singleton
**Article:** https://ankurm.com/singleton-design-pattern-java/
## What this example shows
Six different ways to implement a singleton, compiled and run side by side so their tradeoffs are directly comparable. `AppConfigEager` initializes at class-load time. `AppConfigNaiveLazy` defers initialization but is not thread-safe. `AppConfigSynchronized` fixes thread-safety at the cost of locking on every call. `AppConfigDCL` uses double-checked locking to avoid that per-call lock. `AppConfigHolder` uses the initialization-on-demand holder idiom for lazy, thread-safe initialization with no locking at all. `AppConfigEnum` uses a single-element enum, which the JVM guarantees is a singleton even against reflection and serialization attacks. `Main` exercises all six in one run.
## How to run
```bash
javac singleton/*.java -d out/singleton
java -cp out/singleton singleton.Main
```
Requires Java 25.
## Post Section ↔ File Mapping
| Post Section | File(s) |
|---|---|
| Implementation 1 — Eager Initialization | `AppConfigEager.java` |
| Implementation 2 — Naïve Lazy Initialization | `AppConfigNaiveLazy.java` |
| Implementation 3 — Synchronized Method | `AppConfigSynchronized.java` |
| Implementation 4 — Double-Checked Locking | `AppConfigDCL.java` |
| Implementation 5 — Initialization-on-Demand Holder | `AppConfigHolder.java` |
| Implementation 6 — Enum Singleton | `AppConfigEnum.java` |
| Running All Six Implementations Together | `Main.java` |
Each implementation is renamed to its own class (e.g. `AppConfigEager`, `AppConfigHolder`) so all six can be compiled together in one package and compared directly. The "Breaking via Reflection," "Breaking via Serialization," and Spring `@Component` snippets are illustrative only — they are not part of this repository's runnable example.
Article: https://ankurm.com/singleton-design-pattern-java/
All patterns: https://ankurm.com/design-patterns-java/