Skip to content
Design Patterns Interview Guide: Singleton, Proxy, Spring Source Code & Pitfalls

Design Patterns Interview Guide: Singleton, Proxy, Spring Source Code & Pitfalls

This comprehensive guide covers creational, structural, and behavioral design patterns with Java code examples, Spring framework source code analysis, and common interview pitfalls, enabling developers to move beyond rote memorization to deep understanding.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

Creational Patterns

Singleton Pattern

The article compares four classic implementations: Eager (thread-safe, no lazy loading), Lazy non-thread-safe, Double-Checked Locking (DCL) with volatile, and Static Inner Class (recommended). A table summarizes thread safety, lazy loading, performance, and recommendation.

DCL Pitfall : new Singleton() involves three steps: allocate memory, initialize object, assign reference. Without volatile, instruction reordering may assign reference before initialization, causing other threads to see a partially constructed object and throw NPE. volatile prevents this reordering.

public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }

Static Inner Class leverages JVM class-loading guarantees for thread safety and lazy loading.

public class Singleton { private Singleton() {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }

Enum Singleton resists reflection and serialization attacks.

public enum EnumSingleton { INSTANCE; public void doSomething() {} }

Breaking Singleton : Reflection can invoke private constructor; serialization creates new instance. Defenses: throw exception in constructor if instance exists; implement readResolve() to return the singleton.

Factory Patterns

Three levels: Simple Factory (one factory, parameter-driven, violates Open/Closed Principle), Factory Method (one factory per product, adheres to Open/Closed), Abstract Factory (creates families of related products). Comparison table included.

// Factory Method example interface Phone { void make(); } class IPhone implements Phone { public void make() { System.out.println("生产苹果手机"); } } interface PhoneFactory { Phone createPhone(); } class IPhoneFactory implements PhoneFactory { public Phone createPhone() { return new IPhone(); } }

Builder Pattern

Use when constructor parameters exceed four, many optional, or immutable objects needed. Chain-style implementation with static inner Builder class.

public class User { private final String username; private final String password; private final int age; private final String phone; private final String address; private User(UserBuilder builder) { this.username = builder.username; this.password = builder.password; this.age = builder.age; this.phone = builder.phone; this.address = builder.address; } public static class UserBuilder { private final String username; private final String password; private int age = 0; private String phone = ""; private String address = ""; public UserBuilder(String username, String password) { this.username = username; this.password = password; } public UserBuilder age(int age) { this.age = age; return this; } public UserBuilder phone(String phone) { this.phone = phone; return this; } public UserBuilder address(String address) { this.address = address; return this; } public User build() { return new User(this); } } }

Comparison with telescoping constructors and setters: Builder offers readability, immutability, and validation.

Structural Patterns

Proxy Pattern

Static proxy requires manual proxy class per interface. JDK Dynamic Proxy uses java.lang.reflect.Proxy and InvocationHandler; requires target to implement interface. CGLIB generates subclass via ASM bytecode; target cannot be final, methods cannot be final/private.

Comparison table: JDK uses reflection, CGLIB uses bytecode; JDK requires interface, CGLIB requires non-final class; performance similar post-JDK8; Spring AOP defaults to JDK for interfaces, CGLIB otherwise; can force CGLIB with proxy-target-class=true.

// JDK Dynamic Proxy UserService target = new UserServiceImpl(); UserService proxy = (UserService) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), (proxyObj, method, args) -> { System.out.println("开启事务"); Object result = method.invoke(target, args); System.out.println("提交事务"); return result; }); proxy.save();
// CGLIB Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(UserServiceImpl.class); enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> { System.out.println("开启事务"); Object result = proxy.invokeSuper(obj, args); System.out.println("提交事务"); return result; }); UserServiceImpl proxy = (UserServiceImpl) enhancer.create(); proxy.save();

Adapter Pattern

Converts one interface to another. Object adapter (composition) preferred over class adapter (inheritance). Spring MVC HandlerAdapter adapts various handler types ( @Controller, HttpRequestHandler, Servlet) to a uniform interface.

public interface HandlerAdapter { boolean supports(Object handler); ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object handler); } public class SimpleControllerHandlerAdapter implements HandlerAdapter { public boolean supports(Object handler) { return handler instanceof Controller; } public ModelAndView handle(...) { return ((Controller)handler).handleRequest(req, res); } }

Decorator Pattern

Dynamically adds responsibilities via composition. Java IO ( BufferedReader wraps FileReader) and MyBatis Cache use this. Decorator and component share same interface; proxy controls access; adapter converts interfaces.

interface Coffee { double cost(); String desc(); } class SimpleCoffee implements Coffee { public double cost() { return 10; } public String desc() { return "咖啡"; } } abstract class CoffeeDecorator implements Coffee { protected Coffee coffee; public CoffeeDecorator(Coffee coffee) { this.coffee = coffee; } } class MilkDecorator extends CoffeeDecorator { public MilkDecorator(Coffee coffee) { super(coffee); } public double cost() { return coffee.cost() + 2; } public String desc() { return coffee.desc() + "+牛奶"; } }

Behavioral Patterns

Strategy Pattern

Encapsulates interchangeable algorithms. Context holds strategy interface; concrete strategies implement algorithm. Avoids if-else chains. JDK Comparator, Spring Resource are examples.

interface PaymentStrategy { void pay(double amount); } class AlipayStrategy implements PaymentStrategy { public void pay(double amount) { System.out.println("支付宝支付:" + amount + "元"); } } class Order { private PaymentStrategy paymentStrategy; public void setPaymentStrategy(PaymentStrategy s) { this.paymentStrategy = s; } public void checkout(double amount) { paymentStrategy.pay(amount); } }

Template Method Pattern

Defines algorithm skeleton in abstract class, with abstract steps for subclasses. final template method prevents override. Hook methods provide optional extensions. Spring JdbcTemplate, RestTemplate, Servlet HttpServlet use this.

abstract class CoffeeMaker { public final void makeCoffee() { boilWater(); brewCoffee(); pourInCup(); addCondiments(); } private void boilWater() { System.out.println("烧开水"); } private void pourInCup() { System.out.println("倒入杯中"); } protected abstract void brewCoffee(); protected void addCondiments() {} } class AmericanoMaker extends CoffeeMaker { protected void brewCoffee() { System.out.println("冲泡美式咖啡"); } }

Observer Pattern

One-to-many dependency; subject notifies observers on state change. JDK Observable / Observer (deprecated). Spring ApplicationEvent / ApplicationListener with @EventListener supports async.

interface Subject { void registerObserver(Observer o); void removeObserver(Observer o); void notifyObservers(); } interface Observer { void update(String message); } class NewsAgency implements Subject { private List<Observer> observers = new ArrayList<>(); private String news; public void registerObserver(Observer o) { observers.add(o); } public void removeObserver(Observer o) { observers.remove(o); } public void notifyObservers() { for (Observer o : observers) o.update(news); } public void setNews(String news) { this.news = news; notifyObservers(); } }

Chain of Responsibility

Decouples sender/receiver; request passes along handler chain until handled. Servlet Filter, Spring HandlerInterceptor, Netty ChannelPipeline are examples.

abstract class LeaveHandler { protected LeaveHandler nextHandler; public void setNextHandler(LeaveHandler h) { this.nextHandler = h; } public abstract void handleRequest(int days); } class TeamLeader extends LeaveHandler { public void handleRequest(int days) { if (days <= 3) System.out.println("组长批准" + days + "天"); else if (nextHandler != null) nextHandler.handleRequest(days); } }

Four-Pattern Comparison

Strategy: encapsulate algorithms, interchangeable, uses composition.

Template Method: define skeleton, defer steps, uses inheritance.

Observer: one-to-many notification, register/notify.

Chain of Responsibility: chain handlers, pass request along.

Spring Framework Design Patterns

Core Patterns in Spring

Factory : BeanFactory.getBean() (simple), FactoryBean (factory method), ApplicationContext (abstract factory).

Singleton : Default bean scope; DefaultSingletonBeanRegistry uses ConcurrentHashMap singletonObjects cache.

Proxy : AOP runtime dynamic proxy (JDK/CGLIB). @Transactional creates transaction proxy.

Observer : ApplicationEvent, ApplicationListener, @EventListener for decoupled events.

Template Method : JdbcTemplate, RedisTemplate, RestTemplate encapsulate fixed flows (get connection, execute, release).

Strategy : Resource implementations ( ClassPathResource, FileSystemResource, UrlResource) for loading strategies.

Decorator : BeanWrapperImpl adds property access/conversion; HttpServletRequestWrapper enhances request.

Additional Patterns

Adapter : HandlerAdapter adapts @RequestMapping, HttpRequestHandler, Servlet.

Chain of Responsibility : Servlet Filter chain, Spring Interceptor chain ( preHandle returns false breaks chain), AOP advice chain.

Bridge : Transaction abstraction separates management from implementation (JDBC, JPA, Hibernate).

Iterator : BeanDefinition traversal, collection injection.

Prototype : @Scope("prototype") for new instance each request.

Builder : RestTemplateBuilder, ResponseEntity.ok().body(...) fluent APIs.

Interview Tips

Spring uses patterns to solve real problems: Factory+Singleton manage lifecycle; Proxy+Chain of Responsibility add features non-invasively; Template Method lets developers focus on business logic; Adapter enables framework compatibility; Observer achieves loose coupling. Core philosophy: "Program to interfaces, not implementations."

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Design PatternsJavaInterview PreparationAdapter PatternDecorator PatternProxy PatternSingleton PatternSpring Framework
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.