← 返回首页 ❓ 面试题库
📑 本篇章节导航 (共8章,点击直达)
一、设计原则二、创建型模式三、结构型模式四、行为型模式五、Spring中的设计模式六、重构七、面试高频综合题面试速记口诀

Q132 设计模式与重构实战

20K Java+AI 岗位高频考点 — 设计模式是衡量工程师代码素养的核心标准,面试必考单例、工厂、策略、观察者、模板方法等。覆盖创建型、结构型、行为型模式,Spring中的设计模式,重构原则。

一、设计原则

1. SOLID原则?


S - 单一职责(SRP):一个类只有一个变化的原因
O - 开闭原则(OCP):对扩展开放,对修改关闭
L - 里氏替换(LSP):子类可以替换父类
I - 接口隔离(ISP):接口要小而专一
D - 依赖倒置(DIP):依赖抽象,不依赖具体

Java示例:
// OCP - 策略模式替代if-else
// Bad
public double calculate(Order order) {
    if (order.getType() == NORMAL) return order.getTotal();
    if (order.getType() == VIP) return order.getTotal() * 0.9;
    if (order.getType() == SUPER_VIP) return order.getTotal() * 0.8;
}

// Good
interface DiscountStrategy {
    double calculate(Order order);
}
class NormalDiscount implements DiscountStrategy { ... }
class VipDiscount implements DiscountStrategy { ... }

// DIP - 依赖注入
// Bad:直接new
UserService userService = new UserService(new UserDao());

// Good:依赖注入
@Service
class UserService {
    @Autowired UserDao userDao; // 依赖抽象
}

2. 其他设计原则?


DRY(Don't Repeat Yourself):不要重复代码
KISS(Keep It Simple):保持简单
YAGNI(You Aren't Gonna Need It):不做过度设计
Law of Demeter(最少知道):减少类之间的耦合
Composition over Inheritance:组合优于继承

实际应用:
- DRY → 提取公共方法/工具类
- KISS → 不过度抽象,3个相似才提取
- YAGNI → 不为假想的未来需求设计
- 最少知道 → Builder模式/Fluent API
- 组合 → 用Strategy替代继承层次

二、创建型模式

3. 单例模式?


// 1. 双重检查锁(DCL)
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;
    }
}
// volatile防止指令重排

// 2. 静态内部类(推荐)
public class Singleton {
    private Singleton() {}

    private static class Holder {
        static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return Holder.INSTANCE;
    }
}

// 3. 枚举(最安全,防反射和序列化)
public enum Singleton {
    INSTANCE;
    public void doSomething() { ... }
}

// Spring中的单例:@Component默认单例(Spring容器管理)
// Spring单例不是真正的单例(可以有多个ApplicationContext)

4. 工厂模式?


// 简单工厂
public class NotificationFactory {
    public static Notification create(String type) {
        return switch (type) {
            case "email" -> new EmailNotification();
            case "sms" -> new SmsNotification();
            case "push" -> new PushNotification();
            default -> throw new IllegalArgumentException("Unknown: " + type);
        };
    }
}

// 工厂方法
interface NotificationFactory {
    Notification create();
}

class EmailNotificationFactory implements NotificationFactory {
    public Notification create() { return new EmailNotification(); }
}

// Spring中的工厂:
// FactoryBean<T>:自定义Bean创建逻辑
@Component
public class RestTemplateFactory implements FactoryBean<RestTemplate> {
    @Override
    public RestTemplate getObject() {
        return new RestTemplateBuilder()
            .setConnectTimeout(Duration.ofSeconds(5))
            .build();
    }
    @Override
    public Class<?> getObjectType() { return RestTemplate.class; }
}

5. 建造者模式?


// Lombok @Builder
@Builder
public class HttpRequest {
    private String url;
    private String method;
    private Map<String, String> headers;
    private String body;
    @Builder.Default private int timeout = 5000;
}

// 手写Builder(更多控制)
public class Query {
    private final String table;
    private final List<String> columns;
    private final String where;
    private final int limit;

    private Query(Builder builder) {
        this.table = builder.table;
        this.columns = builder.columns;
        this.where = builder.where;
        this.limit = builder.limit;
    }

    public static Builder builder() { return new Builder(); }

    public static class Builder {
        private String table;
        private List<String> columns = List.of("*");
        private String where;
        private int limit = 100;

        public Builder table(String table) { this.table = table; return this; }
        public Builder columns(String... cols) { this.columns = List.of(cols); return this; }
        public Builder where(String where) { this.where = where; return this; }
        public Builder limit(int limit) { this.limit = limit; return this; }

        public Query build() {
            Objects.requireNonNull(table, "table不能为null");
            return new Query(this);
        }
    }
}

// Spring中的Builder:RestTemplateBuilder, WebClient.Builder

三、结构型模式

6. 代理模式?


// JDK动态代理(接口)
public class LoggingProxy implements InvocationHandler {
    private final Object target;

    public static <T> T create(T target) {
        return (T) Proxy.newProxyInstance(
            target.getClass().getClassLoader(),
            target.getClass().getInterfaces(),
            new LoggingProxy(target));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log.info("调用: {}", method.getName());
        long start = System.currentTimeMillis();
        try {
            return method.invoke(target, args);
        } finally {
            log.info("耗时: {}ms", System.currentTimeMillis() - start);
        }
    }
}

// CGLIB代理(类,Spring默认)
// Spring AOP就是基于代理模式

// Spring中的代理:
// @Transactional → AOP代理 → 开启事务 → 执行方法 → 提交/回滚
// @Cacheable → AOP代理 → 查缓存 → 执行方法 → 写缓存
// @Async → AOP代理 → 提交到线程池

// JDK Proxy vs CGLIB:
// JDK Proxy:只能代理接口,性能好
// CGLIB:可以代理类(不能代理final),生成子类
// Spring Boot 2.x+:默认CGLIB(spring.aop.proxy-target-class=true)

7. 装饰器模式?


// Java IO经典装饰器
InputStream → FileInputStream → BufferedInputStream → GZIPInputStream

// 自定义装饰器
interface DataSource {
    String read();
    void write(String data);
}

class FileDataSource implements DataSource {
    public String read() { /* 读文件 */ }
    public void write(String data) { /* 写文件 */ }
}

class EncryptedDataSource implements DataSource {
    private final DataSource wrappee;

    public String read() {
        return decrypt(wrappee.read());
    }

    public void write(String data) {
        wrappee.encrypt(data);
    }
}

class CompressedDataSource implements DataSource {
    private final DataSource wrappee;

    public String read() {
        return decompress(wrappee.read());
    }

    public void write(String data) {
        wrappee.write(compress(data));
    }
}

// 使用:写入时加密+压缩
DataSource ds = new CompressedDataSource(
    new EncryptedDataSource(new FileDataSource("data.txt")));
ds.write("hello world");

// Spring中的装饰器:
// HttpServletRequestWrapper
// Spring Security Filter Chain

8. 适配器模式?


// 类适配器(继承)
// 对象适配器(组合,推荐)

// Spring中的适配器:
// HandlerAdapter:适配不同的Controller类型
// HttpRequestHandlerAdapter → 处理HttpRequestHandler
// SimpleControllerHandlerAdapter → 处理Controller
// RequestMappingHandlerAdapter → 处理@RequestMapping

// 实际场景:第三方接口适配
interface PaymentGateway {
    PaymentResult pay(PaymentRequest request);
}

class AlipayAdapter implements PaymentGateway {
    private final AlipayClient alipayClient;

    public PaymentResult pay(PaymentRequest request) {
        // 适配Alipay SDK的调用方式
        AlipayTradePayRequest req = new AlipayTradePayRequest();
        req.setBizContent(toJson(request));
        AlipayTradePayResponse resp = alipayClient.execute(req);
        return new PaymentResult(resp.getTradeNo(), resp.isSuccess());
    }
}

四、行为型模式

9. 策略模式?


// Spring中的策略模式最佳实践
public interface PricingStrategy {
    BigDecimal calculate(Order order);
    String getType();
}

@Component
class NormalPricing implements PricingStrategy {
    public BigDecimal calculate(Order order) { return order.getTotal(); }
    public String getType() { return "NORMAL"; }
}

@Component
class VipPricing implements PricingStrategy {
    public BigDecimal calculate(Order order) { return order.getTotal().multiply(new BigDecimal("0.9")); }
    public String getType() { return "VIP"; }
}

@Component
class SuperVipPricing implements PricingStrategy {
    public BigDecimal calculate(Order order) { return order.getTotal().multiply(new BigDecimal("0.8")); }
    public String getType() { return "SUPER_VIP"; }
}

// 策略工厂
@Service
public class PricingFactory {
    private final Map<String, PricingStrategy> strategies;

    // Spring自动注入所有PricingStrategy实现
    public PricingFactory(List<PricingStrategy> strategyList) {
        this.strategies = strategyList.stream()
            .collect(Collectors.toMap(PricingStrategy::getType, Function.identity()));
    }

    public PricingStrategy getStrategy(String type) {
        PricingStrategy strategy = strategies.get(type);
        if (strategy == null) throw new IllegalArgumentException("Unknown: " + type);
        return strategy;
    }
}

10. 观察者模式?


// Java标准库
@EventListener
public void onOrderCreated(OrderCreatedEvent event) {
    // 处理订单创建事件
}

// 发布事件
@Autowired ApplicationEventPublisher publisher;
publisher.publishEvent(new OrderCreatedEvent(orderId));

// Spring事件机制就是观察者模式
// ApplicationEvent → Event → @EventListener

// 异步事件
@Async
@EventListener
public void sendNotification(OrderCreatedEvent event) {
    emailService.sendOrderConfirmation(event.getOrderId());
}

// 条件过滤
@EventListener(condition = "#event.amount > 1000")
public void onLargeOrder(OrderCreatedEvent event) { ... }

// 事务绑定事件
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void afterCommit(OrderCreatedEvent event) { ... }

11. 模板方法模式?


// 抽象模板
public abstract class AbstractDataImporter {
    public final void importData(String filePath) {
        String content = readFile(filePath);      // 1. 读文件
        Object data = parse(content);              // 2. 解析(子类实现)
        validate(data);                            // 3. 校验
        save(data);                                // 4. 保存(子类实现)
        notifySuccess();                           // 5. 通知
    }

    private String readFile(String path) { /* 通用 */ }
    private void validate(Object data) { /* 通用校验 */ }
    private void notifySuccess() { /* 通用通知 */ }

    protected abstract Object parse(String content);
    protected abstract void save(Object data);
}

// Spring中的模板方法:
// AbstractApplicationContext.refresh() → 模板方法
// JdbcTemplate.execute() → 回调模式(变体)
// RestTemplate → 模板 + 回调
// RedisTemplate → 模板 + 回调

12. 责任链模式?


// 责任链
public abstract class Handler {
    private Handler next;
    public Handler setNext(Handler next) { this.next = next; return next; }

    public void handle(Request request) {
        if (doHandle(request) && next != null) {
            next.handle(request);
        }
    }
    protected abstract boolean doHandle(Request request);
}

// Spring中的责任链:
// Filter Chain(Servlet Filter)
// Spring Security Filter Chain
// Spring Interceptor(HandlerInterceptor)

// Spring Security Filter Chain:
HttpSecurity http →
  CorsFilter → CsrfFilter → SessionManagementFilter →
  AuthenticationFilter → AuthorizationFilter → Controller

// 自定义Filter
@Component
public class RateLimitFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp,
                                     FilterChain chain) {
        if (rateLimiter.tryAcquire()) {
            chain.doFilter(req, resp);  // 传递给下一个Filter
        } else {
            resp.setStatus(429);
        }
    }
}

五、Spring中的设计模式

13. Spring设计模式总结?


| 模式 | Spring应用 |
|------|-----------|
| 单例 | Bean默认scope=singleton |
| 工厂 | FactoryBean, BeanFactory |
| 代理 | AOP (@Transactional, @Cacheable) |
| 模板 | JdbcTemplate, RestTemplate, RedisTemplate |
| 观察者 | ApplicationEvent + @EventListener |
| 策略 | Resource接口(ClassPath/File/URL) |
| 适配器 | HandlerAdapter, MvcEndpoint |
| 装饰器 | HttpServletRequestWrapper |
| 责任链 | Filter Chain, Interceptor Chain |
| 建造者 | RestTemplateBuilder, WebClient.Builder |
| 前端控制器 | DispatcherServlet |
| 依赖注入 | @Autowired / @Inject (DIP原则) |

六、重构

14. 代码坏味道与重构?


常见坏味道:
1. 重复代码(Duplicated Code) → 提取方法
2. 过长方法(Long Method) → 分解为小方法
3. 过大类(Large Class) → 拆分职责
4. 过长参数(Long Parameter List) → 引入参数对象
5. 发散式变化(Divergent Change) → 拆分类
6. 霰弹式修改(Shotgun Surgery) → 合并类
7. 依恋情结(Feature Envy) → 移动方法到数据所在类
8. 数据泥团(Data Clumps) → 提取类
9. 基本类型偏执(Primitive Obsession) → 引入值对象
10. switch语句 → 策略模式+工厂

重构手法:
- 提取方法(Extract Method)
- 内联方法(Inline Method)
- 提取变量(Extract Variable)
- 重命名(Rename)
- 移动方法(Move Method)
- 以多态替代条件表达式
- 以策略模式替代类型码

15. 重构示例?


// Before: 典型的坏味道代码
public class OrderService {
    public double calculate(String type, double amount, int years) {
        double discount = 0;
        if (type.equals("VIP")) {
            if (years > 5) discount = 0.3;
            else if (years > 2) discount = 0.2;
            else discount = 0.1;
        } else if (type.equals("SVIP")) {
            if (years > 5) discount = 0.5;
            else discount = 0.3;
        }
        return amount * (1 - discount);
    }
}

// After: 策略模式重构
interface DiscountStrategy {
    double calculate(double amount, int years);
}

@Component("VIP")
class VipDiscount implements DiscountStrategy {
    public double calculate(double amount, int years) {
        double rate = years > 5 ? 0.3 : years > 2 ? 0.2 : 0.1;
        return amount * (1 - rate);
    }
}

@Service
class OrderService {
    @Autowired Map<String, DiscountStrategy> strategies;

    public double calculate(String type, double amount, int years) {
        return strategies.get(type).calculate(amount, years);
    }
}

七、面试高频综合题

16. 如何选择设计模式?


决策树:
创建对象?
├── 一个实例 → 单例
├── 多种类型 → 工厂
├── 复杂构建 → 建造者
└── 克隆 → 原型

结构问题?
├── 接口不兼容 → 适配器
├── 动态扩展 → 装饰器
├── 控制访问 → 代理
└── 简化接口 → 外观

行为问题?
├── 算法切换 → 策略
├── 通知依赖 → 观察者
├── 逐步处理 → 责任链
├── 固定骨架 → 模板方法
└── 解耦调用 → 命令

注意:
- 不要为了用模式而用模式
- 先有问题,再选模式
- 简单场景用if-else就好

17. 你在项目中用过哪些设计模式?


标准回答模板:

"我在项目中主要用到了以下设计模式:

1. 策略模式:支付模块,支持多种支付方式(支付宝/微信/银行卡),
   每种支付方式是独立的策略类,通过Spring自动注册到工厂。

2. 观察者模式:订单状态变更时通知多个下游(库存/积分/物流),
   用Spring Event解耦。

3. 模板方法:数据导入模块,定义导入流程(读取→解析→校验→保存),
   不同格式(CSV/Excel/JSON)只需实现解析和保存。

4. 责任链:请求鉴权流程(Token校验→权限检查→限流检查),
   用Spring Security Filter实现。

5. 建造者:复杂的查询条件构造,用Builder模式保证参数完整性。"

面试速记口诀

SOLID五原则:单一职责、开闭、里氏替换、接口隔离、依赖倒置

>

创建三模式:单例(一个实例)、工厂(创建对象)、建造者(复杂构造)

>

结构三模式:代理(控制访问)、装饰器(动态扩展)、适配器(兼容接口)

>

行为四模式:策略(算法切换)、观察者(通知)、责任链(逐步处理)、模板方法(固定骨架)