Interview
Design Patterns (GoF) — Interview Questions (80+)
See runnable examples in `pkg8patterns`.
For SOLID and OOP design principles, see 02-OopAndSolid.md.
Detailed Questions
1. What are the categories of GoF patterns?
- Short: Creational, Structural, Behavioral.
- Detailed: Creational (object creation: Singleton, Factory Method, Abstract Factory, Builder, Prototype), Structural (composition: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy), Behavioral (interaction: Chain, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor).
- Example: Builder (creational), Decorator (structural), Strategy (behavioral).
2. Where does SOLID fit vs GoF patterns?
- Short: SOLID are principles; GoF patterns are reusable solutions to recurring design problems.
- Detailed: SOLID guides whether a design is maintainable; patterns show how to structure code (e.g. Strategy supports OCP). See 02-OopAndSolid.md for SRP/OCP/LSP/ISP/DIP depth.
- Example: Extract payment algorithms into Strategy beans instead of growing if-else (OCP + Strategy).
3. Singleton: how to implement correctly?
- Short: Enum or static holder idiom.
- Detailed: Enum singletons are thread-safe and serialization/reflection-safe. The holder idiom gives lazy thread-safe init without locking. Double-checked locking needs a
volatilefield. - Example:
enum Config { INSTANCE; }.
4. Factory Method vs Abstract Factory?
- Short: One product via subclass vs families of products.
- Detailed: Factory Method defers instantiation of ONE product to subclasses. Abstract Factory creates FAMILIES of related products through one interface (e.g., a whole UI toolkit).
- Example:
createButton()(factory method) vsGuiFactory{button(); checkbox();}.
5. Strategy vs State?
- Short: Interchangeable algorithms vs behavior tied to internal state with transitions.
- Detailed: Strategy is chosen by the client and usually stateless/independent. State changes the object's behavior as it transitions between states (states often trigger transitions).
- Example: Strategy: sorting order; State: traffic light cycle.
6. Decorator vs Inheritance?
- Short: Add behavior dynamically vs statically.
- Detailed: Decorator composes wrappers at runtime, avoiding a combinatorial explosion of subclasses and allowing feature stacking in any order.
- Example:
new Sugar(new Milk(new Espresso())).
7. Adapter vs Facade vs Proxy?
- Short: Convert interface vs simplify subsystem vs control access.
- Detailed: Adapter changes an interface to one the client expects. Facade provides a simpler unified API over a complex subsystem. Proxy keeps the same interface but controls access (lazy/security/caching/remoting).
- Example:
InputStreamReader(adapter),Computer.start()(facade), lazy-loading proxy.
8. Observer pattern and its pitfalls?
- Short: One-to-many notifications; watch leaks and ordering.
- Detailed: Subjects notify subscribers on change. Pitfalls: memory leaks from forgotten unsubscribes, undefined notification order, and cascading updates. Modern: listeners, reactive streams.
- Example: UI event listeners.
Rapid-Fire (Q → A)
- Singleton intent? → One instance, global access.
- Best singleton? → Enum.
- Lazy singleton idiom? → Static holder.
- DCL needs? → volatile.
- Factory method intent? → Subclass picks class.
- Abstract factory intent? → Families of objects.
- Builder intent? → Step-by-step complex objects.
- Builder real-world? → StringBuilder, HttpRequest.Builder.
- Prototype intent? → Clone existing.
- Prototype concern? → Deep vs shallow copy.
- Adapter intent? → Convert interface.
- Adapter real-world? → InputStreamReader.
- Bridge intent? → Decouple abstraction/impl.
- Bridge real-world? → JDBC.
- Composite intent? → Tree of uniform objects.
- Composite real-world? → File system.
- Decorator intent? → Add behavior dynamically.
- Decorator real-world? → java.io streams.
- Facade intent? → Simplify subsystem.
- Facade real-world? → Service layer.
- Flyweight intent? → Share to save memory.
- Flyweight real-world? → Integer cache, String pool.
- Proxy intent? → Control access.
- Proxy types? → Virtual, protection, remote, caching.
- Proxy real-world? → Spring AOP, Hibernate lazy.
- Chain intent? → Pass request along handlers.
- Chain real-world? → Servlet filters.
- Command intent? → Encapsulate request.
- Command real-world? → Undo, Runnable.
- Interpreter intent? → Evaluate grammar.
- Interpreter real-world? → Regex, SQL.
- Iterator intent? → Sequential access.
- Iterator real-world? → java.util.Iterator.
- Mediator intent? → Centralize comms.
- Mediator real-world? → Chat room, ATC.
- Memento intent? → Capture/restore state.
- Memento real-world? → Editor undo.
- Observer intent? → One-to-many notify.
- Observer real-world? → Listeners, pub/sub.
- State intent? → Behavior by state.
- State real-world? → Order/workflow status.
- Strategy intent? → Interchangeable algorithms.
- Strategy real-world? → Comparator.
- Template method intent? → Algorithm skeleton.
- Template real-world? → AbstractList, HttpServlet.
- Visitor intent? → Add ops without changing elements.
- Visitor real-world? → AST/compiler.
- Visitor downside? → New element type edits all visitors.
- DI pattern? → Provide dependencies externally.
- DI benefit? → Testability, loose coupling.
- IoC? → Framework controls flow/creation.
- Service locator vs DI? → Pull vs push dependencies.
- Repository pattern? → Abstract data access.
- DAO pattern? → Data access object.
- DTO pattern? → Data transfer object.
- MVC? → Model-View-Controller separation.
- Null Object pattern? → Default no-op instance.
- Object pool? → Reuse expensive objects.
- Lazy init? → Defer creation.
- Fluent interface? → Chained methods.
- Immutable object pattern? → Final fields, no setters.
- Double dispatch? → Visitor mechanism.
- SRP smell? → God class.
- OCP technique? → Polymorphism/strategy.
- LSP violation? → Subtype breaks expectations.
- ISP technique? → Split fat interfaces.
- DIP technique? → Program to interfaces.
- DRY? → Don't Repeat Yourself.
- KISS? → Keep It Simple.
- YAGNI? → You Aren't Gonna Need It.
- Composition over inheritance? → More flexible reuse.
- Law of Demeter? → Talk to friends, not strangers.
- Anti-pattern: God object? → Too many responsibilities.
- Anti-pattern: singleton abuse? → Hidden global state.
- Anti-pattern: premature optimization? → Complexity without need.
- Pattern for caching? → Proxy/Decorator/Flyweight.
- Pattern for undo? → Command/Memento.
- Pattern for plugins? → Strategy/Factory.
- Pattern for event handling? → Observer.
- Modern replacement for Visitor? → Sealed types + pattern matching.
- Lambdas replace which patterns? → Strategy/Command/Observer SAMs.
- Choosing a pattern rule? → Match the problem; prefer the simplest solution that communicates intent.