Java 设计模式实战
设计模式是解决常见问题的最佳实践,掌握它们能提高代码质量。
一、创建型模式
1.1 工厂模式
// 简单工厂
public class AnimalFactory {
public static Animal createAnimal(String type) {
return switch (type) {
case "dog" -> new Dog();
case "cat" -> new Cat();
default -> throw new IllegalArgumentException("Unknown type");
};
}
}
// 工厂方法
public interface AnimalFactory {
Animal createAnimal();
}
public class DogFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Dog();
}
}
// 抽象工厂
public interface AnimalFamilyFactory {
Animal createAnimal();
Food createFood();
}
public class DogFamilyFactory implements AnimalFamilyFactory {
@Override
public Animal createAnimal() {
return new Dog();
}
@Override
public Food createFood() {
return new DogFood();
}
}
1.2 建造者模式
// 传统实现
public class Computer {
private final String CPU;
private final String RAM;
private final String storage;
private Computer(Builder builder) {
this.CPU = builder.CPU;
this.RAM = builder.RAM;
this.storage = builder.storage;
}
public static class Builder {
private String CPU;
private String RAM;
private String storage;
public Builder setCPU(String CPU) {
this.CPU = CPU;
return this;
}
public Builder setRAM(String RAM) {
this.RAM = RAM;
return this;
}
public Builder setStorage(String storage) {
this.storage = storage;
return this;
}
public Computer build() {
return new Computer(this);
}
}
}
// 使用
Computer computer = new Computer.Builder()
.setCPU("Intel i7")
.setRAM("16GB")
.setStorage("512GB SSD")
.build();
二、结构型模式
2.1 代理模式
// 静态代理
public interface UserService {
void createUser(String name);
}
public class UserServiceImpl implements UserService {
@Override
public void createUser(String name) {
System.out.println("Creating user: " + name);
}
}
public class UserServiceProxy implements UserService {
private final UserService target;
public UserServiceProxy(UserService target) {
this.target = target;
}
@Override
public void createUser(String name) {
System.out.println("Before creating user");
target.createUser(name);
System.out.println("After creating user");
}
}
2.2 适配器模式
// 类适配器
public class OldSystem {
public void oldMethod() {
System.out.println("Old method");
}
}
public class NewSystem {
public void newMethod() {
System.out.println("New method");
}
}
public class Adapter extends OldSystem implements NewSystem {
@Override
public void newMethod() {
super.oldMethod(); // 复用旧方法
}
}
// 对象适配器
public class ObjectAdapter implements NewSystem {
private final OldSystem oldSystem;
public ObjectAdapter(OldSystem oldSystem) {
this.oldSystem = oldSystem;
}
@Override
public void newMethod() {
oldSystem.oldMethod();
}
}
三、行为型模式
3.1 策略模式
// 策略接口
public interface PaymentStrategy {
void pay(BigDecimal amount);
}
// 具体策略
public class AlipayStrategy implements PaymentStrategy {
@Override
public void pay(BigDecimal amount) {
System.out.println("支付宝支付:" + amount);
}
}
public class WechatPayStrategy implements PaymentStrategy {
@Override
public void pay(BigDecimal amount) {
System.out.println("微信支付:" + amount);
}
}
// 上下文
public class PaymentContext {
private PaymentStrategy strategy;
public void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void executePayment(BigDecimal amount) {
strategy.pay(amount);
}
}
// 使用
PaymentContext context = new PaymentContext();
context.setStrategy(new AlipayStrategy());
context.executePayment(new BigDecimal("100"));
3.2 观察者模式
// 主题接口
public interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
}
// 观察者接口
public interface Observer {
void update(String message);
}
// 具体主题
public class NewsAgency implements Subject {
private final List<Observer> observers = new ArrayList<>();
private String news;
@Override
public void attach(Observer observer) {
observers.add(observer);
}
@Override
public void detach(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(news);
}
}
public void setNews(String news) {
this.news = news;
notifyObservers();
}
}
// 具体观察者
public class NewsChannel implements Observer {
@Override
public void update(String news) {
System.out.println("收到新闻:" + news);
}
}
四、最佳实践
4.1 模式选择
// 创建对象:
// - 简单对象:直接 new
// - 多种类型:工厂模式
// - 复杂对象:建造者模式
// - 单实例:单例模式
// 对象组合:
// - 接口适配:适配器模式
// - 功能增强:装饰器模式
// - 访问控制:代理模式
// 行为抽象:
// - 多算法切换:策略模式
// - 一对多通知:观察者模式
// - 步骤固定:模板方法模式
4.2 避免过度设计
// ❌ 过度设计
// 简单场景使用复杂模式
public class SimpleDataFactoryBuilderProxyDecorator {
// 不必要的复杂
}
// ✅ 简单明了
public class DataService {
public Data getData() {
return new Data();
}
}
五、总结
设计模式核心要点:
| 模式类型 | 模式 | 用途 |
|---|---|---|
| 创建型 | 工厂、建造者、单例 | 对象创建 |
| 结构型 | 代理、适配器、装饰器 | 对象组合 |
| 行为型 | 策略、观察者、模板方法 | 对象协作 |
设计模式是工具而非目标,根据实际需求选择合适的模式。