KatInterview

Singleton, Factory Method and Strategy: Code and Compare in Java

Data Structure DesignModel answer
MediumModel answerData Structure Designdesign-patternsjavasingleton

Last updated

Write Java versions of a lazy thread-safe Singleton, a Factory Method and a Strategy, weigh them against each other, then refactor a Singleton dependency to use injection.

You are asked to demonstrate practical command of three classic object-oriented design patterns in Java.

Part 1: Implement

  1. A Singleton that is both lazily created and safe under concurrent access. Be ready to explain why your approach is correct from a memory-model point of view.
  2. A Factory Method example in which a base class owns a workflow and subclasses decide which concrete collaborator gets created.
  3. A Strategy example in which several interchangeable algorithms sit behind one interface and can be swapped at runtime.

Part 2: Compare

Contrast the three patterns on these axes:

  • the problem each one solves
  • extensibility
  • testability
  • typical risks and costs

Part 3: Refactor

Choose one of your examples, ideally one that reaches a Singleton through a static call, and refactor it to reduce coupling and allow dependency injection. Show the code before and after, and explain what you gain when writing unit tests.

You are not expected to use a DI framework. Plain constructor injection is enough. State any assumptions you make.

Hints

Hint 1

For a lazy, thread-safe Singleton, think about what the JVM already guarantees about class initialization, and about when a nested class is first loaded. If you choose double-checked locking, ask what the field must be declared as, and why.

Hint 2

Factory Method relies on inheritance: the base class calls an overridable creation method and works only against an interface. A plain `switch`-based helper is a different thing (a simple or static factory), so know the difference.

Hint 3

For the refactor, extract an interface for the Singleton's behavior, pass it through the constructor, and keep the real implementation wired up in one place (the composition root). Then show how a test passes in a fake.