Design patterns
patterns1SingletonPattern
- Path
- pkg8patterns/patterns1SingletonPattern.java
- Package
- pkg8patterns
- Study order
- 1
- Run
- Single-file source launch
- Command
- java pkg8patterns/patterns1SingletonPattern.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg8patterns;2 3/*4 * Singleton (Creational)5 * ----------------------6 * INTENT: ensure a class has exactly one instance and a global access point.7 * UML: Singleton - instance: Singleton + getInstance(): Singleton8 * PROS: controlled single instance; lazy init; saves resources.9 * CONS: global state (hard to test); can hide dependencies; concurrency care needed.10 * REAL-WORLD: Runtime, Logger, configuration, connection pool.11 */12public class patterns1SingletonPattern {13 14 // Best practice: enum singleton (thread-safe, serialization-safe).15 enum Config {16 INSTANCE;17 private int version = 1;18 int getVersion() { return version; }19 }20 21 // Classic lazy + thread-safe via holder idiom (lazy, no locking cost).22 static class Logger {23 private Logger() {}24 private static class Holder { static final Logger INSTANCE = new Logger(); }25 static Logger getInstance() { return Holder.INSTANCE; }26 void log(String m) { System.out.println("[LOG] " + m); }27 }28 29 public static void main(String[] args) {30 System.out.println("enum singleton same? " + (Config.INSTANCE == Config.INSTANCE));31 System.out.println("version = " + Config.INSTANCE.getVersion());32 33 Logger a = Logger.getInstance();34 Logger b = Logger.getInstance();35 System.out.println("holder singleton same? " + (a == b));36 a.log("hello from the one and only logger");37 }38}