Introduction to Design Patterns & the Singleton Design Pattern
1. Topic Introduction
Experienced software architects noticed that the same design headaches—like 'how do we guarantee only ONE shared database connection pool or configuration manager exists?'—keep recurring across completely different software projects. Instead of reinventing fragile workarounds, Design Patterns capture proven, battle-tested blueprints for structuring OOP classes. Module 3 focuses on two classic GoF patterns: Singleton and Adapter.
Singleton)Imagine if every department in a college created its own separate Principal whenever someone asked for a signature (new Principal()). Decisions would contradict each other and chaos would ensue! Instead, a college ensures there is ONLY ONE Principal instance, locks the door so nobody outside can hire a second Principal (private constructor), and provides a single Reception Desk (getInstance()) that hands out the exact same Principal reference to everyone who asks!
private static instance field, (2) private constructor, and (3) public static getInstance() method.3. Essential Exam Definitions
4. Detailed Technical Explanation & Syntax
1. Need & Categories of Design Patterns
Why Design Patterns matter: (1) Reuse proven architectural solutions rather than trial-and-error; (2) Establish a shared engineering vocabulary ('let's wrap this legacy API with an Adapter'); (3) Improve maintainability, loose coupling, and testability.
Three classic GoF categories: Creational (object creation — e.g., Singleton), Structural (class/object composition — e.g., Adapter), and Behavioral (object communication).
2. Three Core Elements & Variants of Singleton in Java
Every Java Singleton combines three mandatory pieces:
- 1.
private staticvariable holding the single instance of the class. - 2.
privateconstructor blocking outside classes from executingnew Singleton(). - 3.
public static getInstance()returning that single shared instance. - Variant A — Eager Initialization:
private static final AppConfig INSTANCE = new AppConfig();(simple and inherently thread-safe, created at class load even if never used). - Variant B — Lazy Initialization: Creates instance inside
getInstance()only wheninstance == null(saves memory if unused, though basic lazy isn't thread-safe without synchronization). - Variant C — Thread-Safe Double-Checked Locking (
volatile+synchronized): Checksif (instance == null)outside and insidesynchronized (Singleton.class)so concurrent threads never accidentally create two objects!
5. Working Principle: How Singleton Enforces a Single Object
- Calling
new AppConfig()outside fails at compile time becauseAppConfig()isprivate. - First call to
AppConfig.getInstance()seesinstance == null, creates the sole Heap object, caches it instatic instance, and returns it. - Every subsequent
AppConfig.getInstance()call across the app returns the identical Heap address (ref1 == ref2evaluatestrue).
6. Examination-Ready Diagrams
Singleton Design Pattern
Structural & UML diagram of the Singleton creational pattern ensuring only one shared instance exists across the JVM with a global access point.
- private static Singleton instance: Holds the single shared reference at class level.
- private Singleton(): Private constructor blocks external classes from calling
new Singleton(). - public static getInstance(): Global access method returning the sole instance (creating it once if
null).
- Client 1 calls
Singleton.getInstance(). instanceisnull, sogetInstance()invokes private constructor once and caches reference.- Client 2 calls
Singleton.getInstance()and receives the exact same object reference (c1 == c2istrue).
- Draw a UML class box for
DatabaseConfig/Singletonwith 3 compartments: class name,- static instance : Singleton,- Singleton()++ static getInstance() : Singleton. - Show a self-loop / reference arrow and multiple Client boxes pointing to the SAME single Heap object.
7. Complete Java Code Examples & Tracing
DatabaseConfig) and proves two callers receive the exact same Heap instance.| 1 | class ExamConfigManager { |
| 2 | // 1. volatile private static field ensures visibility across threads |
| 3 | private static volatile ExamConfigManager instance; |
| 4 | private String academicScheme; |
| 5 | |
| 6 | // 2. Private constructor prevents external instantiation via 'new' |
| 7 | private ExamConfigManager() { |
| 8 | this.academicScheme = "KTU 2024 Scheme"; |
| 9 | System.out.println("ExamConfigManager created ONCE."); |
| 10 | } |
| 11 | |
| 12 | // 3. Public static global access point (Thread-safe Double-Checked Locking) |
| 13 | public static ExamConfigManager getInstance() { |
| 14 | if (instance == null) { |
| 15 | synchronized (ExamConfigManager.class) { |
| 16 | if (instance == null) { |
| 17 | instance = new ExamConfigManager(); |
| 18 | } |
| 19 | } |
| 20 | } |
| 21 | return instance; |
| 22 | } |
| 23 | |
| 24 | public String getAcademicScheme() { |
| 25 | return academicScheme; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | public class SingletonConfigDemo { |
| 30 | public static void main(String[] args) { |
| 31 | // ExamConfigManager c = new ExamConfigManager(); // COMPILE ERROR: private constructor! |
| 32 | ExamConfigManager cfg1 = ExamConfigManager.getInstance(); |
| 33 | ExamConfigManager cfg2 = ExamConfigManager.getInstance(); |
| 34 | |
| 35 | System.out.println("Scheme: " + cfg1.getAcademicScheme()); |
| 36 | System.out.println("cfg1 == cfg2 (Same single object)? " + (cfg1 == cfg2)); |
| 37 | } |
| 38 | } |
ExamConfigManager created ONCE. Scheme: KTU 2024 Scheme cfg1 == cfg2 (Same single object)? true
privatestaticvolatilesynchronizedreturn- Leaving the constructor
public(breaks Singleton because any caller can runnew!). - Making
getInstance()non-static (impossible to call without an instance, creating a chicken-and-egg deadlock!). - Forgetting thread safety in lazy initialization when multiple threads call
getInstance()simultaneously.
Advantages
- Guarantees controlled single-instance access to scarce resources (config managers, loggers, connection pools).
- Saves memory by avoiding duplicate heavy object creation and supports lazy initialization.
Limitations / Disadvantages
- Acts like hidden global state, introducing tight coupling and making unit testing/mocking harder.
- Naive lazy implementation breaks under multithreading unless synchronized; also violates Single Responsibility Principle (manages both its own lifecycle AND business logic).
Real-World Applications
java.lang.Runtime.getRuntime()in the JDK itself, application loggers, configuration managers, and thread pools.
Important KTU Exam Points
- Always state the pattern category (Creational), draw Diagram 11, write the 3 mandatory rules (
private staticinstance,privateconstructor,public static getInstance()), and list BOTH Advantages & Limitations!
Memory Techniques & Revision
- Singleton 3 Keys — 'P-P-P':
private staticfield,privateconstructor,public staticgetInstance().
Common Pitfalls to Avoid
- Thinking a Singleton is identical to a class with only
staticmethods—a Singleton is an actual object that can implement interfaces, extend classes, and be lazily initialized!
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: The Singleton pattern is a Creational design pattern ensuring a class produces at most ONE instance across the JVM while providing a global access point.
- Implementation Rules: (1) Declare a
private staticfield holding the sole instance; (2) Make constructorprivateto preventnew; (3) Providepublic static getInstance()to return (or lazily create) the instance. - Advantages: Controls access to shared resources (logging, configuration, thread/DB pools), saves memory, supports lazy initialization.
- Limitations: Introduces global state (tight coupling), complicates unit testing, requires synchronization in multithreaded apps, and mixes lifecycle control with domain logic.
ExamConfigManager code.Quick Understanding Check
1. Why MUST a Singleton class declare its constructor as private?