SOLID principles
| Principle | In one line |
|---|---|
| Single responsibility | A class has one reason to change. |
| Open/closed | Open for extension, closed for modification: add behaviour with new classes, not by editing old ones. |
| Liskov substitution | A subclass must work anywhere its parent is expected, without surprises. |
| Interface segregation | Many small interfaces beat one fat interface. |
| Dependency inversion | Depend on abstractions (interfaces), and receive dependencies from outside (injection). |
Singleton
Exactly one instance, globally accessible. Thread-safe options:
// 1. Holder idiom: lazy and thread-safe without lockspublic final class Config {private Config() {}private static class Holder { static final Config INSTANCE = new Config(); }public static Config get() { return Holder.INSTANCE; }}// 2. Enum: also safe against reflection and serializationpublic enum Registry { INSTANCE; void register(String k) { } }// 3. Double-checked locking needs volatileprivate static volatile Cache instance;public static Cache get() {if (instance == null) synchronized (Cache.class) {if (instance == null) instance = new Cache();}return instance;}
Singletons are global state: they make testing harder. Prefer one instance managed by a dependency-injection container.
Factory and Builder
interface Notifier { void send(String msg); }class EmailNotifier implements Notifier { public void send(String m) { } }class SmsNotifier implements Notifier { public void send(String m) { } }class NotifierFactory { // callers don't name concrete classesstatic Notifier of(String channel) {return switch (channel) {case "email" -> new EmailNotifier();case "sms" -> new SmsNotifier();default -> throw new IllegalArgumentException(channel);};}}
Pizza p = new Pizza.Builder("large") // Builder: readable construction of many optional parts.cheese(true).topping("olives").build();
Strategy, Observer and Decorator
- Strategy: swap an algorithm at run time behind one interface.
Comparatoris a strategy for sorting. - Observer: subjects notify registered listeners of changes (event listeners, pub-sub).
- Decorator: wrap an object to add behaviour without subclassing.
new BufferedReader(new FileReader(f))decorates a reader.
interface Discount { long apply(long price); }class NoDiscount implements Discount { public long apply(long p) { return p; } }class Percent implements Discount {final int pct; Percent(int pct) { this.pct = pct; }public long apply(long p) { return p * (100 - pct) / 100; }}class Checkout {private final Discount discount; // strategy injectedCheckout(Discount d) { discount = d; }long total(long price) { return discount.apply(price); }}
Interview questions
Try answering out loud first, then open the model answer.
Q1Explain the SOLID principles with examples.intermediate
S: a ReportService shouldn't also format emails. O: add a new Discount class rather than editing an if-chain. L: a Square subclass breaking Rectangle.setWidth expectations violates it. I: split Machine into Printer and Scanner. D: OrderService depends on a PaymentGateway interface passed into its constructor.
Q2How do you write a thread-safe singleton?intermediate
Use an enum, or the holder-class idiom (the JVM initializes the nested class lazily and thread-safely), or double-checked locking with a volatile field. A plain lazy check without synchronization can create two instances.
Q3Factory vs Builder?beginner
A factory decides which class to create and hides the concrete type. A builder deals with how to construct one complex object step by step, especially with many optional parameters, avoiding telescoping constructors.
Q4Where do you see the Decorator pattern in the JDK?intermediate
Java I/O: BufferedInputStream(new FileInputStream(...)), Collections.unmodifiableList(list), Collections.synchronizedMap(map). Each wraps an object of the same interface and adds behaviour.
Q5Strategy vs State pattern?advanced
Both delegate to an interchangeable object. In Strategy the client picks the algorithm and it usually stays fixed. In State the object switches its own state object as it moves through a lifecycle (e.g. an order going Pending → Paid → Shipped).
Q6What is dependency injection?intermediate
An object receives its collaborators from outside (usually through the constructor) instead of creating them. It decouples code from concrete classes, makes testing with fakes easy, and is how Spring wires beans.
Quick check
0 of 4 answered