KTU OOP Java2024 Scheme • 60M ESE
MODULE 3/Section 4: Introduction to Design Patterns

Introduction to Design Patterns & the Singleton Design Pattern

HIGH PRIORITY (Prep Guide)Official Syllabus + Supplementary~16 min study
Official KTU 2024 Syllabus Topics Covered Here
Introduction to design patternsNeed for design patternsSingleton design patternSingleton implementation in JavaAdvantages and limitations of Singleton

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.

2. Start From Zero: One Principal's Office for the Entire University (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!

Key Takeaway: Singleton restricts instantiation of a class to ONE shared object across the JVM using 3 ingredients: (1) private static instance field, (2) private constructor, and (3) public static getInstance() method.

3. Essential Exam Definitions

Software Design Pattern
A general, reusable architectural solution (template) to a commonly occurring problem in object-oriented software design, popularized by the 'Gang of Four' (GoF) across Creational, Structural, and Behavioral categories.
Singleton Design Pattern
A Creational design pattern that guarantees a class has only ONE instance in the JVM and provides a global point of access to that single instance.

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 static variable holding the single instance of the class.
  • 2. private constructor blocking outside classes from executing new 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 when instance == null (saves memory if unused, though basic lazy isn't thread-safe without synchronization).
  • Variant C — Thread-Safe Double-Checked Locking (volatile + synchronized): Checks if (instance == null) outside and inside synchronized (Singleton.class) so concurrent threads never accidentally create two objects!

5. Working Principle: How Singleton Enforces a Single Object

  1. Calling new AppConfig() outside fails at compile time because AppConfig() is private.
  2. First call to AppConfig.getInstance() sees instance == null, creates the sole Heap object, caches it in static instance, and returns it.
  3. Every subsequent AppConfig.getInstance() call across the app returns the identical Heap address (ref1 == ref2 evaluates true).

6. Examination-Ready Diagrams

Diagram 11

Singleton Design Pattern

Client ACalls getInstance()Client BCalls getInstance()Singleton- static instance: Singleton- Singleton() // private!+ static getInstance()Creates object ONCE if nullSingle Heap InstanceclientA == clientB (true)

Structural & UML diagram of the Singleton creational pattern ensuring only one shared instance exists across the JVM with a global access point.

Key Components
  • 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).
Step-by-Step Flow
  1. Client 1 calls Singleton.getInstance().
  2. instance is null, so getInstance() invokes private constructor once and caches reference.
  3. Client 2 calls Singleton.getInstance() and receives the exact same object reference (c1 == c2 is true).
How to Draw in KTU Exam
  • Draw a UML class box for DatabaseConfig / Singleton with 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

Lazy & Thread-Safe Singleton Implementation in JavaSingletonConfigDemo.java
Implements a thread-safe Double-Checked Locking Singleton (DatabaseConfig) and proves two callers receive the exact same Heap instance.
1class 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
29public 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}
Expected Output
ExamConfigManager created ONCE.
Scheme: KTU 2024 Scheme
cfg1 == cfg2 (Same single object)? true
Keywords:privatestaticvolatilesynchronizedreturn
Common Exam & Coding Mistakes
  • Leaving the constructor public (breaks Singleton because any caller can run new!).
  • 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 static instance, private constructor, public static getInstance()), and list BOTH Advantages & Limitations!

Memory Techniques & Revision

  • Singleton 3 Keys — 'P-P-P': private static field, private constructor, public static getInstance().

Common Pitfalls to Avoid

  • Thinking a Singleton is identical to a class with only static methods—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 static field holding the sole instance; (2) Make constructor private to prevent new; (3) Provide public 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.
Exam Diagram Note: Draw Diagram 11 (UML Singleton class box + two clients pointing to single Heap instance) and include the ExamConfigManager code.

Quick Understanding Check

1. Why MUST a Singleton class declare its constructor as private?