Java Creational patterns
Controlling how objects are made. In Java most of these questions are really about immutability, thread safety and the container.
3 concepts · 9 interview questions
What this topic covers
Every concept in creational patterns, and the questions each one gets asked as. Where a question links, it has a full write-up.
Singleton
One instance, globally reachable. In a Spring application the container already gives you one per context, which makes the hand-written version mostly an exercise in thread safety.
- How do you implement a thread-safe singleton?
- Why is an enum singleton the safest form?
- How is a Spring singleton bean different from a singleton?
Factory method and abstract factory
Moving the decision of which implementation to create out of the caller. Widely used in the JDK wherever a static method returns an interface.
- What problem does a factory solve that a constructor does not?
- Where does the JDK use a factory method?
- Factory method or abstract factory — what is the difference?
Builder
Constructing an object with many optional parts without a telescoping constructor, and producing an immutable result.
- When is a builder better than a constructor?
- How does a builder help with immutability?
- Do records remove the need for builders?