Java设计模式实战:23种经典模式在企业级项目中的应用

引言

设计模式是软件工程中经过验证的解决方案模板,它们代表了最佳实践,可以帮助开发者解决常见的设计问题。GoF(Gang of Four)提出的23种设计模式至今仍是企业级Java开发的基石。本文将深入探讨这些模式在实际项目中的应用场景和实现方式。


一、创建型模式(Creational Patterns)

创建型模式关注对象的创建机制,使系统独立于对象的创建、组合和表示方式。

1. 单例模式(Singleton Pattern)

应用场景:数据库连接池、配置管理器、日志记录器

企业实战案例:Spring容器中的Bean默认作用域

public class DatabaseConnectionPool {
    private static volatile DatabaseConnectionPool instance;
    private final List<Connection> connectionPool;
    
    private DatabaseConnectionPool() {
        connectionPool = new ArrayList<>();
        initializePool();
    }
    
    public static DatabaseConnectionPool getInstance() {
        if (instance == null) {
            synchronized (DatabaseConnectionPool.class) {
                if (instance == null) {
                    instance = new DatabaseConnectionPool();
                }
            }
        }
        return instance;
    }
    
    public Connection getConnection() {
        // 从连接池获取连接
        return connectionPool.isEmpty() ? createNewConnection() 
            : connectionPool.remove(0);
    }
}

最佳实践

  • 使用双重检查锁定确保线程安全
  • 考虑使用枚举实现单例(更简洁且天然防止反序列化)
  • 在Spring环境中优先使用IoC容器管理

2. 工厂方法模式(Factory Method Pattern)

应用场景:支付系统、消息队列客户端、数据源切换

企业实战案例:多支付渠道集成

// 支付接口
public interface PaymentService {
    PaymentResult process(PaymentRequest request);
}

// 具体实现
public class AlipayService implements PaymentService {
    @Override
    public PaymentResult process(PaymentRequest request) {
        // 支付宝支付逻辑
        return new PaymentResult("alipay", "success");
    }
}

public class WechatPayService implements PaymentService {
    @Override
    public PaymentResult process(PaymentRequest request) {
        // 微信支付逻辑
        return new PaymentResult("wechat", "success");
    }
}

// 工厂类
public class PaymentServiceFactory {
    public static PaymentService createPaymentService(String type) {
        switch (type.toLowerCase()) {
            case "alipay":
                return new AlipayService();
            case "wechat":
                return new WechatPayService();
            case "unionpay":
                return new UnionPayService();
            default:
                throw new IllegalArgumentException("不支持的支付类型: " + type);
        }
    }
}

优势

  • 解耦对象创建和使用
  • 易于扩展新的支付方式
  • 符合开闭原则

3. 抽象工厂模式(Abstract Factory Pattern)

应用场景:跨数据库平台支持、UI主题切换、多云服务提供商

企业实战案例:多数据库支持系统

// 抽象工厂接口
public interface DatabaseFactory {
    Connection createConnection();
    Query createQuery();
    Transaction createTransaction();
}

// MySQL工厂
public class MySQLFactory implements DatabaseFactory {
    @Override
    public Connection createConnection() {
        return new MySQLConnection();
    }
    
    @Override
    public Query createQuery() {
        return new MySQLQuery();
    }
    
    @Override
    public Transaction createTransaction() {
        return new MySQLTransaction();
    }
}

// Oracle工厂
public class OracleFactory implements DatabaseFactory {
    @Override
    public Connection createConnection() {
        return new OracleConnection();
    }
    
    @Override
    public Query createQuery() {
        return new OracleQuery();
    }
    
    @Override
    public Transaction createTransaction() {
        return new OracleTransaction();
    }
}

4. 建造者模式(Builder Pattern)

应用场景:复杂对象构建、HTTP请求构建、SQL查询构建

企业实战案例:构建复杂的业务对象

public class Order {
    private final String orderId;
    private final String customerId;
    private final List<OrderItem> items;
    private final Address shippingAddress;
    private final PaymentMethod paymentMethod;
    private final String couponCode;
    private final boolean giftWrap;
    
    private Order(Builder builder) {
        this.orderId = builder.orderId;
        this.customerId = builder.customerId;
        this.items = builder.items;
        this.shippingAddress = builder.shippingAddress;
        this.paymentMethod = builder.paymentMethod;
        this.couponCode = builder.couponCode;
        this.giftWrap = builder.giftWrap;
    }
    
    public static class Builder {
        private String orderId;
        private String customerId;
        private List<OrderItem> items = new ArrayList<>();
        private Address shippingAddress;
        private PaymentMethod paymentMethod;
        private String couponCode;
        private boolean giftWrap;
        
        public Builder orderId(String orderId) {
            this.orderId = orderId;
            return this;
        }
        
        public Builder customerId(String customerId) {
            this.customerId = customerId;
            return this;
        }
        
        public Builder addItem(OrderItem item) {
            this.items.add(item);
            return this;
        }
        
        public Builder shippingAddress(Address address) {
            this.shippingAddress = address;
            return this;
        }
        
        public Builder paymentMethod(PaymentMethod method) {
            this.paymentMethod = method;
            return this;
        }
        
        public Builder couponCode(String code) {
            this.couponCode = code;
            return this;
        }
        
        public Builder giftWrap(boolean wrap) {
            this.giftWrap = wrap;
            return this;
        }
        
        public Order build() {
            // 验证必填字段
            if (orderId == null || customerId == null || items.isEmpty()) {
                throw new IllegalStateException("订单缺少必填信息");
            }
            return new Order(this);
        }
    }
}

// 使用示例
Order order = new Order.Builder()
    .orderId("ORD001")
    .customerId("CUST001")
    .addItem(new OrderItem("PROD001", 2))
    .shippingAddress(new Address("北京市朝阳区"))
    .paymentMethod(PaymentMethod.ALIPAY)
    .couponCode("DISCOUNT20")
    .giftWrap(true)
    .build();

5. 原型模式(Prototype Pattern)

应用场景:对象克隆、缓存预热、配置模板

企业实战案例:文档模板系统

public class DocumentTemplate implements Cloneable {
    private String templateId;
    private String title;
    private List<Section> sections;
    private Map<String, String> metadata;
    
    @Override
    public DocumentTemplate clone() {
        try {
            DocumentTemplate cloned = (DocumentTemplate) super.clone();
            // 深拷贝可变对象
            cloned.sections = new ArrayList<>(this.sections);
            cloned.metadata = new HashMap<>(this.metadata);
            return cloned;
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException("克隆失败", e);
        }
    }
    
    // 基于模板创建新文档
    public Document createDocument(String documentId) {
        DocumentTemplate template = this.clone();
        return new Document(documentId, template);
    }
}

二、结构型模式(Structural Patterns)

结构型模式关注类和对象的组合,形成更大的结构。

6. 适配器模式(Adapter Pattern)

应用场景:第三方库集成、遗留系统改造、接口兼容

企业实战案例:统一日志框架

// 目标接口
public interface Logger {
    void log(String level, String message);
}

// 旧系统的日志类
public class LegacyLogger {
    public void writeLog(int severity, String msg) {
        System.out.println("[" + severity + "] " + msg);
    }
}

// 适配器
public class LoggerAdapter implements Logger {
    private LegacyLogger legacyLogger;
    
    public LoggerAdapter(LegacyLogger legacyLogger) {
        this.legacyLogger = legacyLogger;
    }
    
    @Override
    public void log(String level, String message) {
        int severity = convertLevel(level);
        legacyLogger.writeLog(severity, message);
    }
    
    private int convertLevel(String level) {
        switch (level.toUpperCase()) {
            case "ERROR": return 1;
            case "WARN": return 2;
            case "INFO": return 3;
            default: return 4;
        }
    }
}

7. 桥接模式(Bridge Pattern)

应用场景:跨平台应用、多维度变化的系统、消息发送系统

企业实战案例:多渠道消息推送

// 实现接口
public interface MessageSender {
    void send(String message, String recipient);
}

// 具体实现
public class EmailSender implements MessageSender {
    @Override
    public void send(String message, String recipient) {
        System.out.println("发送邮件到 " + recipient + ": " + message);
    }
}

public class SmsSender implements MessageSender {
    @Override
    public void send(String message, String recipient) {
        System.out.println("发送短信到 " + recipient + ": " + message);
    }
}

// 抽象部分
public abstract class Notification {
    protected MessageSender sender;
    
    public Notification(MessageSender sender) {
        this.sender = sender;
    }
    
    public abstract void notify(String message, String recipient);
}

// 扩展抽象
public class UrgentNotification extends Notification {
    public UrgentNotification(MessageSender sender) {
        super(sender);
    }
    
    @Override
    public void notify(String message, String recipient) {
        message = "[紧急] " + message;
        sender.send(message, recipient);
        // 可以发送多次或使用不同渠道
        sender.send(message, recipient);
    }
}

public class NormalNotification extends Notification {
    public NormalNotification(MessageSender sender) {
        super(sender);
    }
    
    @Override
    public void notify(String message, String recipient) {
        sender.send(message, recipient);
    }
}

8. 组合模式(Composite Pattern)

应用场景:组织架构、文件系统、菜单结构

企业实战案例:企业组织架构管理

// 组件接口
public interface OrganizationComponent {
    String getName();
    void display(int depth);
    double calculateSalary();
}

// 叶子节点 - 员工
public class Employee implements OrganizationComponent {
    private String name;
    private String position;
    private double salary;
    
    public Employee(String name, String position, double salary) {
        this.name = name;
        this.position = position;
        this.salary = salary;
    }
    
    @Override
    public String getName() {
        return name;
    }
    
    @Override
    public void display(int depth) {
        System.out.println("-".repeat(depth) + name + " (" + position + ")");
    }
    
    @Override
    public double calculateSalary() {
        return salary;
    }
}

// 组合节点 - 部门
public class Department implements OrganizationComponent {
    private String name;
    private List<OrganizationComponent> children = new ArrayList<>();
    
    public Department(String name) {
        this.name = name;
    }
    
    public void add(OrganizationComponent component) {
        children.add(component);
    }
    
    public void remove(OrganizationComponent component) {
        children.remove(component);
    }
    
    @Override
    public String getName() {
        return name;
    }
    
    @Override
    public void display(int depth) {
        System.out.println("-".repeat(depth) + name + " [部门]");
        for (OrganizationComponent child : children) {
            child.display(depth + 2);
        }
    }
    
    @Override
    public double calculateSalary() {
        return children.stream()
            .mapToDouble(OrganizationComponent::calculateSalary)
            .sum();
    }
}

9. 装饰器模式(Decorator Pattern)

应用场景:功能增强、日志记录、权限控制

企业实战案例:数据流处理管道

// 组件接口
public interface DataProcessor {
    String process(String data);
}

// 具体组件
public class BasicDataProcessor implements DataProcessor {
    @Override
    public String process(String data) {
        return data;
    }
}

// 装饰器基类
public abstract class DataProcessorDecorator implements DataProcessor {
    protected DataProcessor processor;
    
    public DataProcessorDecorator(DataProcessor processor) {
        this.processor = processor;
    }
}

// 加密装饰器
public class EncryptionDecorator extends DataProcessorDecorator {
    public EncryptionDecorator(DataProcessor processor) {
        super(processor);
    }
    
    @Override
    public String process(String data) {
        String processed = processor.process(data);
        return encrypt(processed);
    }
    
    private String encrypt(String data) {
        // 加密逻辑
        return Base64.getEncoder().encodeToString(data.getBytes());
    }
}

// 压缩装饰器
public class CompressionDecorator extends DataProcessorDecorator {
    public CompressionDecorator(DataProcessor processor) {
        super(processor);
    }
    
    @Override
    public String process(String data) {
        String processed = processor.process(data);
        return compress(processed);
    }
    
    private String compress(String data) {
        // 压缩逻辑
        return "compressed(" + data + ")";
    }
}

// 使用示例
DataProcessor processor = new EncryptionDecorator(
    new CompressionDecorator(
        new BasicDataProcessor()
    )
);
String result = processor.process("敏感数据");

10. 外观模式(Facade Pattern)

应用场景:复杂子系统封装、第三方库简化、微服务聚合

企业实战案例:订单处理系统

// 子系统类
public class InventoryService {
    public boolean checkStock(String productId, int quantity) {
        System.out.println("检查库存: " + productId);
        return true;
    }
    
    public void reduceStock(String productId, int quantity) {
        System.out.println("减少库存: " + productId);
    }
}

public class PaymentService {
    public boolean processPayment(String orderId, double amount) {
        System.out.println("处理支付: " + orderId);
        return true;
    }
}

public class ShippingService {
    public String createShipment(String orderId, Address address) {
        System.out.println("创建物流订单: " + orderId);
        return "SHIP-" + orderId;
    }
}

public class NotificationService {
    public void sendOrderConfirmation(String customerId, String orderId) {
        System.out.println("发送订单确认: " + orderId);
    }
}

// 外观类
public class OrderFacade {
    private InventoryService inventoryService;
    private PaymentService paymentService;
    private ShippingService shippingService;
    private NotificationService notificationService;
    
    public OrderFacade() {
        this.inventoryService = new InventoryService();
        this.paymentService = new PaymentService();
        this.shippingService = new ShippingService();
        this.notificationService = new NotificationService();
    }
    
    public boolean placeOrder(Order order) {
        try {
            // 1. 检查库存
            if (!inventoryService.checkStock(order.getProductId(), order.getQuantity())) {
                return false;
            }
            
            // 2. 处理支付
            if (!paymentService.processPayment(order.getOrderId(), order.getAmount())) {
                return false;
            }
            
            // 3. 减少库存
            inventoryService.reduceStock(order.getProductId(), order.getQuantity());
            
            // 4. 创建物流订单
            String shipmentId = shippingService.createShipment(
                order.getOrderId(), 
                order.getShippingAddress()
            );
            
            // 5. 发送通知
            notificationService.sendOrderConfirmation(
                order.getCustomerId(), 
                order.getOrderId()
            );
            
            return true;
        } catch (Exception e) {
            // 处理异常和回滚
            return false;
        }
    }
}

11. 享元模式(Flyweight Pattern)

应用场景:对象池、缓存系统、字符串常量池

企业实战案例:图标资源管理

// 享元接口
public interface Icon {
    void render(int x, int y);
}

// 具体享元
public class ImageIcon implements Icon {
    private final String imagePath;
    private final byte[] imageData;
    
    public ImageIcon(String imagePath) {
        this.imagePath = imagePath;
        this.imageData = loadImageData(imagePath);
        System.out.println("加载图标: " + imagePath);
    }
    
    @Override
    public void render(int x, int y) {
        System.out.println("渲染图标 " + imagePath + " 在 (" + x + "," + y + ")");
    }
    
    private byte[] loadImageData(String path) {
        // 加载图片数据
        return new byte[1024];
    }
}

// 享元工厂
public class IconFactory {
    private static final Map<String, Icon> iconCache = new HashMap<>();
    
    public static Icon getIcon(String iconType) {
        Icon icon = iconCache.get(iconType);
        if (icon == null) {
            icon = new ImageIcon("/icons/" + iconType + ".png");
            iconCache.put(iconType, icon);
        }
        return icon;
    }
    
    public static int getCacheSize() {
        return iconCache.size();
    }
}

// 使用示例
public class FileExplorer {
    public void displayFiles(List<File> files) {
        for (File file : files) {
            Icon icon = IconFactory.getIcon(file.getType());
            icon.render(file.getX(), file.getY());
        }
    }
}

12. 代理模式(Proxy Pattern)

应用场景:远程代理、虚拟代理、保护代理、缓存代理

企业实战案例:服务调用缓存代理

// 服务接口
public interface UserService {
    User getUserById(String userId);
}

// 真实服务
public class UserServiceImpl implements UserService {
    @Override
    public User getUserById(String userId) {
        System.out.println("从数据库查询用户: " + userId);
        // 模拟数据库查询
        return new User(userId, "张三", "zhangsan@example.com");
    }
}

// 缓存代理
public class CachedUserServiceProxy implements UserService {
    private UserService realService;
    private Map<String, User> cache = new ConcurrentHashMap<>();
    private static final long CACHE_EXPIRE_TIME = 300000; // 5分钟
    private Map<String, Long> cacheTime = new ConcurrentHashMap<>();
    
    public CachedUserServiceProxy(UserService realService) {
        this.realService = realService;
    }
    
    @Override
    public User getUserById(String userId) {
        // 检查缓存
        if (cache.containsKey(userId)) {
            Long cachedAt = cacheTime.get(userId);
            if (System.currentTimeMillis() - cachedAt < CACHE_EXPIRE_TIME) {
                System.out.println("从缓存返回用户: " + userId);
                return cache.get(userId);
            }
        }
        
        // 调用真实服务
        User user = realService.getUserById(userId);
        
        // 更新缓存
        cache.put(userId, user);
        cacheTime.put(userId, System.currentTimeMillis());
        
        return user;
    }
}

三、行为型模式(Behavioral Patterns)

行为型模式关注对象之间的通信和职责分配。

13. 责任链模式(Chain of Responsibility Pattern)

应用场景:请求审批流程、异常处理、日志级别过滤

企业实战案例:订单审批流程

// 审批处理器抽象类
public abstract class ApprovalHandler {
    protected ApprovalHandler nextHandler;
    
    public void setNextHandler(ApprovalHandler handler) {
        this.nextHandler = handler;
    }
    
    public abstract void handleRequest(PurchaseRequest request);
}

// 部门经理审批
public class DepartmentManagerHandler extends ApprovalHandler {
    private static final double APPROVAL_LIMIT = 10000;
    
    @Override
    public void handleRequest(PurchaseRequest request) {
        if (request.getAmount() <= APPROVAL_LIMIT) {
            System.out.println("部门经理审批通过: " + request.getDescription());
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

// 总经理审批
public class GeneralManagerHandler extends ApprovalHandler {
    private static final double APPROVAL_LIMIT = 50000;
    
    @Override
    public void handleRequest(PurchaseRequest request) {
        if (request.getAmount() <= APPROVAL_LIMIT) {
            System.out.println("总经理审批通过: " + request.getDescription());
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

// CEO审批
public class CEOHandler extends ApprovalHandler {
    @Override
    public void handleRequest(PurchaseRequest request) {
        System.out.println("CEO审批通过: " + request.getDescription());
    }
}

// 使用示例
ApprovalHandler deptManager = new DepartmentManagerHandler();
ApprovalHandler generalManager = new GeneralManagerHandler();
ApprovalHandler ceo = new CEOHandler();

deptManager.setNextHandler(generalManager);
generalManager.setNextHandler(ceo);

deptManager.handleRequest(new PurchaseRequest("办公用品", 5000));
deptManager.handleRequest(new PurchaseRequest("服务器设备", 30000));
deptManager.handleRequest(new PurchaseRequest("新办公室装修", 100000));

14. 命令模式(Command Pattern)

应用场景:事务操作、撤销重做、任务队列

企业实战案例:文档编辑器

// 命令接口
public interface Command {
    void execute();
    void undo();
}

// 接收者
public class Document {
    private StringBuilder content = new StringBuilder();
    
    public void insertText(String text) {
        content.append(text);
    }
    
    public void deleteText(int length) {
        int start = Math.max(0, content.length() - length);
        content.delete(start, content.length());
    }
    
    public String getContent() {
        return content.toString();
    }
}

// 具体命令
public class InsertTextCommand implements Command {
    private Document document;
    private String text;
    
    public InsertTextCommand(Document document, String text) {
        this.document = document;
        this.text = text;
    }
    
    @Override
    public void execute() {
        document.insertText(text);
    }
    
    @Override
    public void undo() {
        document.deleteText(text.length());
    }
}

// 调用者
public class DocumentEditor {
    private Stack<Command> history = new Stack<>();
    
    public void executeCommand(Command command) {
        command.execute();
        history.push(command);
    }
    
    public void undo() {
        if (!history.isEmpty()) {
            Command command = history.pop();
            command.undo();
        }
    }
}

15. 解释器模式(Interpreter Pattern)

应用场景:表达式解析、规则引擎、配置文件解析

企业实战案例:简单规则引擎

// 抽象表达式
public interface Expression {
    boolean interpret(Map<String, Object> context);
}

// 终结符表达式
public class VariableExpression implements Expression {
    private String key;
    
    public VariableExpression(String key) {
        this.key = key;
    }
    
    @Override
    public boolean interpret(Map<String, Object> context) {
        Object value = context.get(key);
        return value != null && (Boolean) value;
    }
}

// 非终结符表达式 - AND
public class AndExpression implements Expression {
    private Expression left;
    private Expression right;
    
    public AndExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }
    
    @Override
    public boolean interpret(Map<String, Object> context) {
        return left.interpret(context) && right.interpret(context);
    }
}

// 非终结符表达式 - OR
public class OrExpression implements Expression {
    private Expression left;
    private Expression right;
    
    public OrExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }
    
    @Override
    public boolean interpret(Map<String, Object> context) {
        return left.interpret(context) || right.interpret(context);
    }
}

// 使用示例:折扣规则引擎
// 规则:(是会员 AND 购买金额>100) OR 是VIP
Expression rule = new OrExpression(
    new AndExpression(
        new VariableExpression("isMember"),
        new VariableExpression("amountOver100")
    ),
    new VariableExpression("isVIP")
);

Map<String, Object> context = new HashMap<>();
context.put("isMember", true);
context.put("amountOver100", true);
context.put("isVIP", false);

boolean eligible = rule.interpret(context); // true

16. 迭代器模式(Iterator Pattern)

应用场景:集合遍历、数据分页、树形结构遍历

企业实战案例:自定义数据结构遍历

// 迭代器接口
public interface Iterator<T> {
    boolean hasNext();
    T next();
}

// 聚合接口
public interface Aggregate<T> {
    Iterator<T> createIterator();
}

// 具体聚合 - 员工集合
public class EmployeeCollection implements Aggregate<Employee> {
    private List<Employee> employees = new ArrayList<>();
    
    public void addEmployee(Employee employee) {
        employees.add(employee);
    }
    
    @Override
    public Iterator<Employee> createIterator() {
        return new EmployeeIterator(employees);
    }
}

// 具体迭代器
public class EmployeeIterator implements Iterator<Employee> {
    private List<Employee> employees;
    private int position = 0;
    
    public EmployeeIterator(List<Employee> employees) {
        this.employees = employees;
    }
    
    @Override
    public boolean hasNext() {
        return position < employees.size();
    }
    
    @Override
    public Employee next() {
        if (hasNext()) {
            return employees.get(position++);
        }
        throw new NoSuchElementException();
    }
}

// 使用示例
EmployeeCollection collection = new EmployeeCollection();
collection.addEmployee(new Employee("张三", "开发部"));
collection.addEmployee(new Employee("李四", "测试部"));

Iterator<Employee> iterator = collection.createIterator();
while (iterator.hasNext()) {
    Employee emp = iterator.next();
    System.out.println(emp.getName());
}

17. 中介者模式(Mediator Pattern)

应用场景:聊天室、航空管制系统、UI组件交互

企业实战案例:聊天室系统

// 中介者接口
public interface ChatMediator {
    void sendMessage(String message, User user);
    void addUser(User user);
}

// 具体中介者
public class ChatRoom implements ChatMediator {
    private List<User> users = new ArrayList<>();
    
    @Override
    public void addUser(User user) {
        users.add(user);
    }
    
    @Override
    public void sendMessage(String message, User sender) {
        for (User user : users) {
            // 不发送给自己
            if (user != sender) {
                user.receive(message, sender);
            }
        }
    }
}

// 用户类
public class User {
    private String name;
    private ChatMediator mediator;
    
    public User(String name, ChatMediator mediator) {
        this.name = name;
        this.mediator = mediator;
    }
    
    public void send(String message) {
        System.out.println(name + " 发送: " + message);
        mediator.sendMessage(message, this);
    }
    
    public void receive(String message, User from) {
        System.out.println(name + " 收到来自 " + from.getName() + " 的消息: " + message);
    }
    
    public String getName() {
        return name;
    }
}

// 使用示例
ChatMediator chatRoom = new ChatRoom();

User user1 = new User("张三", chatRoom);
User user2 = new User("李四", chatRoom);
User user3 = new User("王五", chatRoom);

chatRoom.addUser(user1);
chatRoom.addUser(user2);
chatRoom.addUser(user3);

user1.send("大家好!");

18. 备忘录模式(Memento Pattern)

应用场景:撤销操作、快照保存、游戏存档

企业实战案例:游戏进度保存

// 备忘录
public class GameMemento {
    private final int level;
    private final int score;
    private final int health;
    private final String timestamp;
    
    public GameMemento(int level, int score, int health) {
        this.level = level;
        this.score = score;
        this.health = health;
        this.timestamp = LocalDateTime.now().toString();
    }
    
    // Getters
    public int getLevel() { return level; }
    public int getScore() { return score; }
    public int getHealth() { return health; }
    public String getTimestamp() { return timestamp; }
}

// 原发器
public class Game {
    private int level;
    private int score;
    private int health;
    
    public void play() {
        level++;
        score += 100;
        health -= 10;
        System.out.println("当前状态 - 等级: " + level + ", 分数: " + score + ", 生命: " + health);
    }
    
    public GameMemento save() {
        System.out.println("保存游戏进度...");
        return new GameMemento(level, score, health);
    }
    
    public void restore(GameMemento memento) {
        this.level = memento.getLevel();
        this.score = memento.getScore();
        this.health = memento.getHealth();
        System.out.println("恢复游戏进度 - 等级: " + level + ", 分数: " + score + ", 生命: " + health);
    }
}

// 管理者
public class GameCaretaker {
    private Stack<GameMemento> saveStates = new Stack<>();
    
    public void save(GameMemento memento) {
        saveStates.push(memento);
    }
    
    public GameMemento undo() {
        if (!saveStates.isEmpty()) {
            return saveStates.pop();
        }
        return null;
    }
}

19. 观察者模式(Observer Pattern)

应用场景:事件监听、消息订阅、MVC架构

企业实战案例:股票价格监控系统

// 观察者接口
public interface StockObserver {
    void update(String stockSymbol, double price);
}

// 主题接口
public interface StockSubject {
    void attach(StockObserver observer);
    void detach(StockObserver observer);
    void notifyObservers();
}

// 具体主题
public class Stock implements StockSubject {
    private String symbol;
    private double price;
    private List<StockObserver> observers = new ArrayList<>();
    
    public Stock(String symbol) {
        this.symbol = symbol;
    }
    
    @Override
    public void attach(StockObserver observer) {
        observers.add(observer);
    }
    
    @Override
    public void detach(StockObserver observer) {
        observers.remove(observer);
    }
    
    @Override
    public void notifyObservers() {
        for (StockObserver observer : observers) {
            observer.update(symbol, price);
        }
    }
    
    public void setPrice(double price) {
        this.price = price;
        notifyObservers();
    }
}

// 具体观察者 - 投资者
public class Investor implements StockObserver {
    private String name;
    private double threshold;
    
    public Investor(String name, double threshold) {
        this.name = name;
        this.threshold = threshold;
    }
    
    @Override
    public void update(String stockSymbol, double price) {
        System.out.println(name + " 收到通知: " + stockSymbol + " 价格更新为 " + price);
        if (price < threshold) {
            System.out.println(name + " 决定买入 " + stockSymbol);
        }
    }
}

// 使用示例
Stock appleStock = new Stock("AAPL");

Investor investor1 = new Investor("张三", 150.0);
Investor investor2 = new Investor("李四", 140.0);

appleStock.attach(investor1);
appleStock.attach(investor2);

appleStock.setPrice(155.5);
appleStock.setPrice(145.0);

20. 状态模式(State Pattern)

应用场景:订单状态管理、工作流引擎、游戏角色状态

企业实战案例:订单状态管理

// 状态接口
public interface OrderState {
    void handlePayment(OrderContext context);
    void handleShipment(OrderContext context);
    void handleDelivery(OrderContext context);
    void handleCancel(OrderContext context);
}

// 上下文
public class OrderContext {
    private OrderState state;
    private String orderId;
    
    public OrderContext(String orderId) {
        this.orderId = orderId;
        this.state = new PendingPaymentState();
    }
    
    public void setState(OrderState state) {
        this.state = state;
    }
    
    public void pay() {
        state.handlePayment(this);
    }
    
    public void ship() {
        state.handleShipment(this);
    }
    
    public void deliver() {
        state.handleDelivery(this);
    }
    
    public void cancel() {
        state.handleCancel(this);
    }
    
    public String getOrderId() {
        return orderId;
    }
}

// 具体状态 - 待支付
public class PendingPaymentState implements OrderState {
    @Override
    public void handlePayment(OrderContext context) {
        System.out.println("订单 " + context.getOrderId() + " 支付成功");
        context.setState(new PaidState());
    }
    
    @Override
    public void handleShipment(OrderContext context) {
        System.out.println("订单未支付,无法发货");
    }
    
    @Override
    public void handleDelivery(OrderContext context) {
        System.out.println("订单未支付,无法配送");
    }
    
    @Override
    public void handleCancel(OrderContext context) {
        System.out.println("订单 " + context.getOrderId() + " 已取消");
        context.setState(new CancelledState());
    }
}

// 具体状态 - 已支付
public class PaidState implements OrderState {
    @Override
    public void handlePayment(OrderContext context) {
        System.out.println("订单已支付,无需重复支付");
    }
    
    @Override
    public void handleShipment(OrderContext context) {
        System.out.println("订单 " + context.getOrderId() + " 开始发货");
        context.setState(new ShippedState());
    }
    
    @Override
    public void handleDelivery(OrderContext context) {
        System.out.println("订单未发货,无法配送");
    }
    
    @Override
    public void handleCancel(OrderContext context) {
        System.out.println("订单 " + context.getOrderId() + " 已取消,开始退款");
        context.setState(new CancelledState());
    }
}

// 具体状态 - 已发货
public class ShippedState implements OrderState {
    @Override
    public void handlePayment(OrderContext context) {
        System.out.println("订单已支付");
    }
    
    @Override
    public void handleShipment(OrderContext context) {
        System.out.println("订单已发货");
    }
    
    @Override
    public void handleDelivery(OrderContext context) {
        System.out.println("订单 " + context.getOrderId() + " 配送完成");
        context.setState(new DeliveredState());
    }
    
    @Override
    public void handleCancel(OrderContext context) {
        System.out.println("订单已发货,无法取消");
    }
}

// 其他状态类似实现...
public class DeliveredState implements OrderState {
    @Override
    public void handlePayment(OrderContext context) {
        System.out.println("订单已完成");
    }
    
    @Override
    public void handleShipment(OrderContext context) {
        System.out.println("订单已完成");
    }
    
    @Override
    public void handleDelivery(OrderContext context) {
        System.out.println("订单已送达");
    }
    
    @Override
    public void handleCancel(OrderContext context) {
        System.out.println("订单已完成,无法取消");
    }
}

public class CancelledState implements OrderState {
    @Override
    public void handlePayment(OrderContext context) {
        System.out.println("订单已取消");
    }
    
    @Override
    public void handleShipment(OrderContext context) {
        System.out.println("订单已取消");
    }
    
    @Override
    public void handleDelivery(OrderContext context) {
        System.out.println("订单已取消");
    }
    
    @Override
    public void handleCancel(OrderContext context) {
        System.out.println("订单已取消");
    }
}

21. 策略模式(Strategy Pattern)

应用场景:算法选择、支付方式、排序算法、折扣计算

企业实战案例:促销策略系统

// 策略接口
public interface DiscountStrategy {
    double calculateDiscount(double originalPrice);
    String getDescription();
}

// 具体策略 - 无折扣
public class NoDiscountStrategy implements DiscountStrategy {
    @Override
    public double calculateDiscount(double originalPrice) {
        return originalPrice;
    }
    
    @Override
    public String getDescription() {
        return "无折扣";
    }
}

// 具体策略 - 固定折扣
public class PercentageDiscountStrategy implements DiscountStrategy {
    private double percentage;
    
    public PercentageDiscountStrategy(double percentage) {
        this.percentage = percentage;
    }
    
    @Override
    public double calculateDiscount(double originalPrice) {
        return originalPrice * (1 - percentage / 100);
    }
    
    @Override
    public String getDescription() {
        return percentage + "% 折扣";
    }
}

// 具体策略 - 满减
public class FullReductionStrategy implements DiscountStrategy {
    private double threshold;
    private double reduction;
    
    public FullReductionStrategy(double threshold, double reduction) {
        this.threshold = threshold;
        this.reduction = reduction;
    }
    
    @Override
    public double calculateDiscount(double originalPrice) {
        if (originalPrice >= threshold) {
            return originalPrice - reduction;
        }
        return originalPrice;
    }
    
    @Override
    public String getDescription() {
        return "满" + threshold + "减" + reduction;
    }
}

// 上下文
public class ShoppingCart {
    private List<Product> products = new ArrayList<>();
    private DiscountStrategy discountStrategy;
    
    public void addProduct(Product product) {
        products.add(product);
    }
    
    public void setDiscountStrategy(DiscountStrategy strategy) {
        this.discountStrategy = strategy;
    }
    
    public double calculateTotal() {
        double total = products.stream()
            .mapToDouble(Product::getPrice)
            .sum();
        
        if (discountStrategy != null) {
            total = discountStrategy.calculateDiscount(total);
            System.out.println("应用策略: " + discountStrategy.getDescription());
        }
        
        return total;
    }
}

// 使用示例
ShoppingCart cart = new ShoppingCart();
cart.addProduct(new Product("笔记本电脑", 5999.0));
cart.addProduct(new Product("鼠标", 99.0));

// 应用不同策略
cart.setDiscountStrategy(new NoDiscountStrategy());
System.out.println("总价: " + cart.calculateTotal());

cart.setDiscountStrategy(new PercentageDiscountStrategy(10));
System.out.println("总价: " + cart.calculateTotal());

cart.setDiscountStrategy(new FullReductionStrategy(5000, 300));
System.out.println("总价: " + cart.calculateTotal());

22. 模板方法模式(Template Method Pattern)

应用场景:框架设计、工作流程、数据处理流程

企业实战案例:数据导入流程

// 抽象类
public abstract class DataImporter {
    
    // 模板方法
    public final void importData(String filePath) {
        try {
            // 1. 验证文件
            if (!validateFile(filePath)) {
                System.out.println("文件验证失败");
                return;
            }
            
            // 2. 读取数据
            List<String> rawData = readData(filePath);
            
            // 3. 解析数据
            List<Object> parsedData = parseData(rawData);
            
            // 4. 验证数据
            if (!validateData(parsedData)) {
                System.out.println("数据验证失败");
                return;
            }
            
            // 5. 保存数据
            saveData(parsedData);
            
            // 6. 钩子方法 - 可选的后处理
            afterImport(parsedData);
            
            System.out.println("数据导入成功");
        } catch (Exception e) {
            handleError(e);
        }
    }
    
    // 抽象方法 - 子类必须实现
    protected abstract List<String> readData(String filePath);
    protected abstract List<Object> parseData(List<String> rawData);
    protected abstract void saveData(List<Object> data);
    
    // 钩子方法 - 子类可选实现
    protected boolean validateFile(String filePath) {
        return filePath != null && !filePath.isEmpty();
    }
    
    protected boolean validateData(List<Object> data) {
        return data != null && !data.isEmpty();
    }
    
    protected void afterImport(List<Object> data) {
        // 默认什么都不做
    }
    
    protected void handleError(Exception e) {
        System.err.println("导入错误: " + e.getMessage());
    }
}

// 具体实现 - CSV导入
public class CsvDataImporter extends DataImporter {
    
    @Override
    protected List<String> readData(String filePath) {
        System.out.println("读取CSV文件: " + filePath);
        // 读取CSV文件逻辑
        return Arrays.asList("row1,data1", "row2,data2", "row3,data3");
    }
    
    @Override
    protected List<Object> parseData(List<String> rawData) {
        System.out.println("解析CSV数据");
        List<Object> parsed = new ArrayList<>();
        for (String row : rawData) {
            String[] fields = row.split(",");
            parsed.add(new CsvRecord(fields));
        }
        return parsed;
    }
    
    @Override
    protected void saveData(List<Object> data) {
        System.out.println("保存CSV数据到数据库: " + data.size() + " 条记录");
    }
    
    @Override
    protected void afterImport(List<Object> data) {
        System.out.println("发送CSV导入完成通知");
    }
}

// 具体实现 - Excel导入
public class ExcelDataImporter extends DataImporter {
    
    @Override
    protected List<String> readData(String filePath) {
        System.out.println("读取Excel文件: " + filePath);
        // 读取Excel文件逻辑
        return Arrays.asList("sheet1", "sheet2");
    }
    
    @Override
    protected List<Object> parseData(List<String> rawData) {
        System.out.println("解析Excel数据");
        List<Object> parsed = new ArrayList<>();
        for (String sheet : rawData) {
            parsed.add(new ExcelSheet(sheet));
        }
        return parsed;
    }
    
    @Override
    protected void saveData(List<Object> data) {
        System.out.println("保存Excel数据到数据库: " + data.size() + " 个工作表");
    }
    
    @Override
    protected boolean validateFile(String filePath) {
        return super.validateFile(filePath) && filePath.endsWith(".xlsx");
    }
}

// 使用示例
DataImporter csvImporter = new CsvDataImporter();
csvImporter.importData("data.csv");

DataImporter excelImporter = new ExcelDataImporter();
excelImporter.importData("data.xlsx");

23. 访问者模式(Visitor Pattern)

应用场景:对象结构遍历、编译器、报表生成

企业实战案例:员工薪资计算系统

// 访问者接口
public interface EmployeeVisitor {
    void visit(FullTimeEmployee employee);
    void visit(PartTimeEmployee employee);
    void visit(Contractor employee);
}

// 元素接口
public interface Employee {
    void accept(EmployeeVisitor visitor);
    String getName();
}

// 具体元素 - 全职员工
public class FullTimeEmployee implements Employee {
    private String name;
    private double monthlySalary;
    
    public FullTimeEmployee(String name, double monthlySalary) {
        this.name = name;
        this.monthlySalary = monthlySalary;
    }
    
    @Override
    public void accept(EmployeeVisitor visitor) {
        visitor.visit(this);
    }
    
    public String getName() {
        return name;
    }
    
    public double getMonthlySalary() {
        return monthlySalary;
    }
}

// 具体元素 - 兼职员工
public class PartTimeEmployee implements Employee {
    private String name;
    private double hourlyRate;
    private int hoursWorked;
    
    public PartTimeEmployee(String name, double hourlyRate, int hoursWorked) {
        this.name = name;
        this.hourlyRate = hourlyRate;
        this.hoursWorked = hoursWorked;
    }
    
    @Override
    public void accept(EmployeeVisitor visitor) {
        visitor.visit(this);
    }
    
    public String getName() {
        return name;
    }
    
    public double getHourlyRate() {
        return hourlyRate;
    }
    
    public int getHoursWorked() {
        return hoursWorked;
    }
}

// 具体元素 - 合同工
public class Contractor implements Employee {
    private String name;
    private double projectFee;
    
    public Contractor(String name, double projectFee) {
        this.name = name;
        this.projectFee = projectFee;
    }
    
    @Override
    public void accept(EmployeeVisitor visitor) {
        visitor.visit(this);
    }
    
    public String getName() {
        return name;
    }
    
    public double getProjectFee() {
        return projectFee;
    }
}

// 具体访问者 - 薪资计算
public class SalaryCalculator implements EmployeeVisitor {
    private double totalSalary = 0;
    
    @Override
    public void visit(FullTimeEmployee employee) {
        double salary = employee.getMonthlySalary();
        totalSalary += salary;
        System.out.println(employee.getName() + " (全职) 薪资: " + salary);
    }
    
    @Override
    public void visit(PartTimeEmployee employee) {
        double salary = employee.getHourlyRate() * employee.getHoursWorked();
        totalSalary += salary;
        System.out.println(employee.getName() + " (兼职) 薪资: " + salary);
    }
    
    @Override
    public void visit(Contractor employee) {
        double fee = employee.getProjectFee();
        totalSalary += fee;
        System.out.println(employee.getName() + " (合同工) 费用: " + fee);
    }
    
    public double getTotalSalary() {
        return totalSalary;
    }
}

// 具体访问者 - 年假计算
public class VacationCalculator implements EmployeeVisitor {
    
    @Override
    public void visit(FullTimeEmployee employee) {
        int vacationDays = 20;
        System.out.println(employee.getName() + " (全职) 年假: " + vacationDays + " 天");
    }
    
    @Override
    public void visit(PartTimeEmployee employee) {
        int vacationDays = 10;
        System.out.println(employee.getName() + " (兼职) 年假: " + vacationDays + " 天");
    }
    
    @Override
    public void visit(Contractor employee) {
        System.out.println(employee.getName() + " (合同工) 无年假");
    }
}

// 使用示例
List<Employee> employees = Arrays.asList(
    new FullTimeEmployee("张三", 10000),
    new PartTimeEmployee("李四", 100, 80),
    new Contractor("王五", 50000)
);

SalaryCalculator salaryCalc = new SalaryCalculator();
VacationCalculator vacationCalc = new VacationCalculator();

for (Employee employee : employees) {
    employee.accept(salaryCalc);
    employee.accept(vacationCalc);
}

System.out.println("总薪资支出: " + salaryCalc.getTotalSalary());

四、设计模式在Spring框架中的应用

4.1 单例模式

Spring容器中的Bean默认是单例的,通过IoC容器管理生命周期。

4.2 工厂模式

BeanFactory和ApplicationContext使用工厂模式创建和管理Bean。

4.3 代理模式

Spring AOP使用动态代理实现切面编程,支持JDK动态代理和CGLIB。

4.4 模板方法模式

JdbcTemplate、RestTemplate、RedisTemplate等使用模板方法模式。

4.5 观察者模式

Spring事件机制使用观察者模式,通过ApplicationEvent和ApplicationListener实现。

4.6 适配器模式

Spring MVC中的HandlerAdapter将不同类型的Handler适配到统一接口。


五、企业级项目最佳实践

5.1 设计模式选择原则

  1. 需求驱动:根据实际业务需求选择合适的模式
  2. 简单优先:不要过度设计,保持代码简洁
  3. 可扩展性:考虑未来的变化和扩展需求
  4. 团队共识:确保团队成员理解和认同所使用的模式

5.2 常见误区

  1. 过度使用:不要为了使用设计模式而使用
  2. 生搬硬套:要根据实际情况灵活应用
  3. 忽视性能:某些模式会带来性能开销
  4. 缺乏文档:使用模式时要有清晰的文档说明

5.3 实施建议

  1. 代码审查:通过Code Review确保正确使用设计模式
  2. 持续重构:随着需求变化适时调整设计
  3. 性能测试:验证设计模式对性能的影响
  4. 知识分享:团队内部分享设计模式的使用经验

六、总结

设计模式是软件工程的智慧结晶,但它们不是银弹。在企业级Java项目中:

  1. 创建型模式帮助我们灵活地创建对象
  2. 结构型模式帮助我们组织类和对象的结构
  3. 行为型模式帮助我们定义对象间的通信方式

关键是要理解每种模式的本质和适用场景,在实际项目中灵活运用。设计模式不是目的,而是手段。我们的目标始终是写出高质量、易维护、可扩展的代码。

记住:简单就是美,优雅源于实践。


参考资料

  • 《设计模式:可复用面向对象软件的基础》- GoF
  • 《Head First 设计模式》
  • 《Java设计模式》
  • Spring Framework官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天天进步2015

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值