Singleton: The Only Key

Singleton: The Only Key in Java: Imagine a Vault that only has One Key. No matter how many people want to enter, they must all use the same key.

Concept Explanation

Imagine a Vault that only has One Key. No matter how many people want to enter, they must all use the same key. The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.


Code Implementation (Thread-Safe)

public class DatabaseConnection {
    // 1. Private static instance
    private static DatabaseConnection instance;

    // 2. Private constructor (No one else can say 'new')
    private DatabaseConnection() {}

    // 3. Public static method to get the instance
    public static synchronized DatabaseConnection getInstance() {
        if (instance == null) {
            instance = new DatabaseConnection();
        }
        return instance;
    }
}

Strategy Pattern: The Game Character

Imagine a Warrior in a game.

  • If he picks up a Sword, his attack() method uses sword logic.
  • If he picks up a Bow, his attack() method uses bow logic.

The Strategy pattern allows you to change the behavior of an object at runtime by plugging in different "Strategies."


Best Practices

  • Don't Overuse Singleton: It can make unit testing difficult because it creates "Global State."
  • Prefer Composition (Strategy): Instead of making 50 subclasses of a Bird (FlyingBird, SwimmingBird, etc.), give the Bird a FlyBehavior object that you can swap.

Practice Exercises

  1. The Factory: Research the Factory Pattern. How can you create a method called getAnimal(String type) that returns either a Dog or a Cat based on the input?
  2. The Double-Checked Locking: In the Singleton code above, research why using synchronized on the whole method might be slow. What is "Double-Checked Locking"?
  3. The Observer: Research the Observer Pattern. How does it allow a "News Agency" to automatically notify 100 different "Subscribers" when a new story is published?