What Do Interviewers Really Test When They Ask About Design Patterns?
The article shows that interviewers don’t just want you to list design patterns; they assess your ability to identify real scenarios, solve concrete problems, justify trade‑offs, and discuss implementation details, illustrated with payment and order‑processing examples in Java and Spring.
Why Most Candidates Fail the Design‑Pattern Question
Many developers have memorized the 23 classic design patterns, yet only a few can answer interview questions effectively.
Real Interview Scene
Candidate A simply listed several patterns. Candidate B explained how the payment module used a factory pattern to support multiple payment channels, later switched to a factory‑method for better extensibility, and also described the use of a strategy pattern for order handling. Candidate B received the offer while Candidate A didn’t pass the second round.
The interviewer was not asking for a checklist of patterns but for concrete usage in real projects.
Four Aspects Interviewers Evaluate
Scenario‑identification ability – Can you map a business need to a suitable pattern? (e.g., need to create related objects → Factory pattern; need dynamic algorithm switching → Strategy pattern; need to decouple objects → Observer/Event‑driven; need a unified interface for different objects → Adapter pattern.)
Pain‑point solving ability – What specific problem did the pattern solve? (e.g., replacing hard‑coded if‑else for payment channels with a factory reduced coupling and allowed new channels without code changes; using Strategy split order‑type logic, cutting maintenance cost by 50%.)
Trade‑off reasoning ability – Why choose this pattern over alternatives? (e.g., simple factory limits extensibility, violating the Open‑Closed Principle; Strategy fits algorithm switching better than State.)
Implementation‑detail ability – How was the pattern implemented and what pitfalls were encountered? (e.g., Spring’s FactoryBean caused circular‑dependency issues, solved by using @Configuration + @Bean; Strategy registration with a Map caused concurrency problems, solved with ConcurrentHashMap.)
These four points form the "problem → solution → effect" chain interviewers expect.
Project‑Level Applications
Scenario 1: Payment Module – Factory Pattern
Pain point : Payment channels change frequently; using if‑else or switch leads to hard‑coded logic and high risk.
Solution : Leverage Spring’s automatic injection of all PaymentStrategy beans into a Map<String, PaymentStrategy> to build a non‑intrusive factory.
public interface PaymentStrategy {
/** 支付核心逻辑 */
PaymentResult pay(String orderId, BigDecimal amount);
/** 获取支付渠道编码 */
String getChannelCode();
} @Component
public class AlipayStrategy implements PaymentStrategy {
@Override
public PaymentResult pay(String orderId, BigDecimal amount) {
log.info("调用支付宝SDK支付,订单:{},金额:{}", orderId, amount);
// 调用第三方SDK
return PaymentResult.success("ALIPAY_TRADE_NO_123");
}
@Override
public String getChannelCode() { return "ALIPAY"; }
} @Component
public class PaymentStrategyFactory {
// Spring 自动注入所有 PaymentStrategy Bean
@Autowired
private Map<String, PaymentStrategy> strategyMap;
/** 根据渠道编码获取策略 */
public PaymentStrategy getStrategy(String channelCode) {
PaymentStrategy strategy = strategyMap.get(channelCode);
if (strategy == null) {
throw new BizException("不支持的支付渠道:" + channelCode);
}
return strategy;
}
/** 获取所有支持的渠道 */
public Set<String> getSupportedChannels() { return strategyMap.keySet(); }
} @Service
public class PaymentService {
@Autowired
private PaymentStrategyFactory factory;
public void payOrder(String channelCode, String orderId, BigDecimal amount) {
PaymentStrategy strategy = factory.getStrategy(channelCode);
PaymentResult result = strategy.pay(orderId, amount);
log.info("支付结果:{}", result);
}
}Adding a new channel such as DigitalCurrency only requires a new DigitalCurrencyStrategy class annotated with @Component; the factory and service remain unchanged, satisfying the Open‑Closed Principle and keeping the service decoupled.
Scenario 2: Order Processing – Strategy + Chain of Responsibility
Pain point : During peak sales, order creation involves risk control, inventory deduction, and notification. A monolithic method becomes spaghetti code.
Solution : Define a chain of handler nodes, each implementing a single responsibility, and combine with strategy for algorithm selection.
public interface OrderHandlerChain {
/** 处理订单 */
void handle(OrderContext context);
/** 设置下一个节点 */
void setNext(OrderHandlerChain next);
} @Component
public class RiskControlHandler implements OrderHandlerChain {
@Override
public void handle(OrderContext context) {
Order order = context.getOrder();
// 简单风控:单笔金额 > 10,000 标记为高风险
if (order.getAmount().compareTo(new BigDecimal("10000")) > 0) {
order.setRiskLevel("HIGH");
log.warn("风控告警:订单{}金额过大", order.getId());
}
if (getNext() != null) { getNext().handle(context); }
}
} @Configuration
public class OrderHandlerConfig {
@Autowired private RiskControlHandler riskControlHandler;
@Autowired private InventoryHandler inventoryHandler;
@Autowired private NotificationHandler notificationHandler;
@Bean
public OrderHandlerChain orderHandlerChain() {
riskControlHandler.setNext(inventoryHandler);
inventoryHandler.setNext(notificationHandler);
notificationHandler.setNext(null); // 链尾
return riskControlHandler; // 返回链头
}
} @Service
public class OrderCreateService {
@Autowired private OrderHandlerChain handlerChain;
@Transactional
public void createOrder(Order order) {
OrderContext context = new OrderContext(order);
// 只调用一次,后续流程由责任链完成
handlerChain.handle(context);
}
}Each handler follows the Single‑Responsibility Principle. The setNext method allows flexible reordering; for example, removing the risk‑control handler during a flash sale requires only a configuration change.
How to Answer the Design‑Pattern Question in an Interview
Correct Answer Template
"In my project I mainly used the Factory pattern, Strategy pattern, and Observer pattern. For the payment module we introduced a factory to create different payment objects. Previously we used if‑else, which tightly coupled the code; after applying the factory, adding a new payment method only required a new class, adhering to the Open‑Closed Principle. The order‑processing module employed the Strategy pattern because different order types required different algorithms. Splitting the logic into separate strategy classes made the code clearer and reduced maintenance cost by about 50%. The notification module used the Observer pattern to decouple systems when an order status changed, avoiding hard‑coded callbacks. "
Incorrect Answer Template
"I have used Factory, Singleton, Strategy, Template Method, Chain of Responsibility..."
The former demonstrates depth and real experience; the latter is merely a list of names.
Understanding the four evaluation points and being able to discuss concrete implementations, trade‑offs, and pitfalls will help you give a deep, experience‑driven answer that interviewers look for.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer1970
Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
