Java设计模式精解:23种设计模式实战指南

设计模式是软件开发解决常见问题的最佳实践方案,本文将详细介绍Java中常用的设计模式及其实践应用。

创建型模式

单例模式(Singleton)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 双重检查锁定实现
public class Singleton {
    private volatile static Singleton instance;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

// 枚举实现
public enum SingletonEnum {
    INSTANCE;
    
    public void doSomething() {
        // 业务方法
    }
}

工厂方法模式(Factory Method)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public interface Product {}

public class ConcreteProductA implements Product {}
public class ConcreteProductB implements Product {}

public abstract class Creator {
    abstract Product createProduct();
    
    public void someOperation() {
        Product product = createProduct();
        // 使用产品
    }
}

public class ConcreteCreator extends Creator {
    @Override
    Product createProduct() {
        return new ConcreteProductA();
    }
}

结构型模式

适配器模式(Adapter)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 目标接口
public interface Target {
    void request();
}

// 需要适配的类
public class Adaptee {
    public void specificRequest() {
        System.out.println("Specific request");
    }
}

// 适配器
public class Adapter implements Target {
    private Adaptee adaptee;
    
    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
    
    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

装饰器模式(Decorator)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public interface Component {
    void operation();
}

public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("ConcreteComponent operation");
    }
}

public abstract class Decorator implements Component {
    protected Component component;
    
    public Decorator(Component component) {
        this.component = component;
    }
    
    @Override
    public void operation() {
        component.operation();
    }
}

public class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }
    
    @Override
    public void operation() {
        super.operation();
        addedBehavior();
    }
    
    private void addedBehavior() {
        System.out.println("Added behavior");
    }
}

行为型模式

观察者模式(Observer)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public interface Observer {
    void update(String message);
}

public class ConcreteObserver implements Observer {
    private String name;
    
    public ConcreteObserver(String name) {
        this.name = name;
    }
    
    @Override
    public void update(String message) {
        System.out.println(name + " received: " + message);
    }
}

public class Subject {
    private List<Observer> observers = new ArrayList<>();
    
    public void attach(Observer observer) {
        observers.add(observer);
    }
    
    public void detach(Observer observer) {
        observers.remove(observer);
    }
    
    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}

策略模式(Strategy)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public interface Strategy {
    void execute();
}

public class ConcreteStrategyA implements Strategy {
    @Override
    public void execute() {
        System.out.println("Executing strategy A");
    }
}

public class ConcreteStrategyB implements Strategy {
    @Override
    public void execute() {
        System.out.println("Executing strategy B");
    }
}

public class Context {
    private Strategy strategy;
    
    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public void executeStrategy() {
        strategy.execute();
    }
}

实际应用场景

1. Spring框架中的设计模式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// 工厂模式示例
@Configuration
public class BeanConfig {
    @Bean
    public UserService userService() {
        return new UserServiceImpl();
    }
}

// 代理模式示例
@Aspect
@Component
public class LoggingAspect {
    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("Before method: " + joinPoint.getSignature().getName());
    }
}

2. JDBC中的设计模式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 模板方法模式
public abstract class JdbcTemplate {
    public final void execute() {
        Connection conn = null;
        try {
            conn = getConnection();
            doExecute(conn);
        } finally {
            closeConnection(conn);
        }
    }
    
    protected abstract void doExecute(Connection conn);
}

设计模式的选择

何时使用工厂模式

  • 当创建对象的过程比较复杂
  • 当系统需要解耦对象的创建和使用

何时使用单例模式

  • 当需要确保系统中只有一个实例
  • 当这个唯一实例需要被系统其他对象共享访问

最佳实践

  1. 设计模式的选择要基于实际需求
  2. 不要过度使用设计模式
  3. 注意设计模式的适用场景
  4. 遵循SOLID原则

常见问题

1. 模式的误用

1
2
3
4
5
6
7
8
// 反面示例:过度使用单例
public class BadSingleton {
    private static BadSingleton instance = new BadSingleton();
    private Configuration config;
    private Database database;
    private Cache cache;
    // 过多的职责违反了单一职责原则
}

2. 模式的组合

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 工厂模式和单例模式的组合
public class SingletonFactory {
    private static Map<String, Object> instances = new ConcurrentHashMap<>();
    
    public static Object getInstance(String className) {
        return instances.computeIfAbsent(className, k -> {
            try {
                return Class.forName(k).newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }
}

总结

设计模式是面向对象设计中的重要工具,合理使用设计模式可以提高代码的可维护性和可扩展性。

参考资料

  • 设计模式:可复用面向对象软件的基础
  • Head First设计模式
  • Effective Java
使用绝夜之城强力驱动