Java的设计模式详解
摘要:设计模式是软件工程中解决常见问题的经典方案。本文结合Java语言特性,深入解析常用设计模式的核心思想、实现方式及实际应用场景,帮助开发者提升代码质量和可维护性。
一、设计模式概述
1.1 什么是设计模式?
设计模式(Design Pattern)是经过验证的、可重复使用的代码设计经验总结,分为创建型、结构型和行为型三大类,共23种经典模式。
1.2 学习设计模式的意义
- 提高代码复用性
- 增强系统扩展性
- 提升团队协作效率
- 优化代码结构
二、创建型模式实践
2.1 单例模式(Singleton)
场景:全局唯一对象(如配置管理器)
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;
}
}
特点:双重检查锁实现线程安全
2.2 工厂模式(Factory)
场景:对象创建逻辑封装
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() {
System.out.println("绘制圆形");
}
}
class ShapeFactory {
public Shape getShape(String type) {
if ("CIRCLE".equalsIgnoreCase(type)) {
return new Circle();
}
return null;
}
}
优势:解耦客户端与具体实现类
三、结构型模式解析
3.1 适配器模式(Adapter)
场景:接口兼容转换
class LegacySystem {
public void legacyRequest() {
System.out.println("旧系统请求");
}
}
interface NewSystem {
void request();
}
class Adapter implements NewSystem {
private LegacySystem legacy = new LegacySystem();
public void request() {
legacy.legacyRequest();
}
}
3.2 装饰器模式(Decorator)
场景:动态扩展功能
interface Coffee {
double getCost();
}
class BasicCoffee implements Coffee {
public double getCost() { return 2.0; }
}
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;
public CoffeeDecorator(Coffee coffee) {
this.decoratedCoffee = coffee;
}
}
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) {
super(coffee);
}
public double getCost() {
return super.decoratedCoffee.getCost() + 0.5;
}
}
四、行为型模式应用
4.1 观察者模式(Observer)
场景:事件驱动系统
interface Observer {
void update(String message);
}
class ConcreteObserver implements Observer {
public void update(String message) {
System.out.println("收到通知:" + message);
}
}
class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer o) {
observers.add(o);
}
public void notifyObservers(String message) {
observers.forEach(o -> o.update(message));
}
}
4.2 策略模式(Strategy)
场景:算法灵活切换
interface PaymentStrategy {
void pay(double amount);
}
class AlipayStrategy implements PaymentStrategy {
public void pay(double amount) {
System.out.println("支付宝支付:" + amount);
}
}
class PaymentContext {
private PaymentStrategy strategy;
public void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void executePayment(double amount) {
strategy.pay(amount);
}
}
五、模式选择指南
模式类型 | 典型场景 | 常用模式 |
---|---|---|
创建型 | 对象创建管理 | 工厂、单例、建造者 |
结构型 | 类/对象组合 | 适配器、代理、装饰器 |
行为型 | 对象交互 | 观察者、策略、模板方法 |