当前位置: 首页 > news >正文

Java设计模式:系统性解析与核心模式


一、设计模式三大分类总览

  1. 创建型模式(5种)
    核心目标:对象创建的优化与解耦

单例模式(Singleton)

工厂模式(Factory)

抽象工厂模式(Abstract Factory)

建造者模式(Builder)

原型模式(Prototype)

  1. 结构型模式(7种)
    核心目标:类与对象组合的灵活架构

适配器模式(Adapter)

装饰器模式(Decorator)

代理模式(Proxy)

外观模式(Facade)

桥接模式(Bridge)

组合模式(Composite)

享元模式(Flyweight)

  1. 行为型模式(11种)
    核心目标:对象间的交互与职责分配

观察者模式(Observer)

策略模式(Strategy)

命令模式(Command)

责任链模式(Chain of Responsibility)

状态模式(State)

模板方法模式(Template Method)

迭代器模式(Iterator)

中介者模式(Mediator)

备忘录模式(Memento)

访问者模式(Visitor)

解释器模式(Interpreter)

二、创建型模式深度解析

1. 单例模式(Singleton)——对象创建的终极控制

核心特征:全局唯一实例 + 延迟初始化 + 线程安全

演进式实现对比
// 1. 饿汉式(线程安全但立即加载)
public class EagerSingleton {
    private static final EagerSingleton INSTANCE = new EagerSingleton();
    private EagerSingleton() {}
    public static EagerSingleton getInstance() { return INSTANCE; }
}

// 2. 双重校验锁(DCL)实现
public class DCLSingleton {
    private static volatile DCLSingleton instance; // volatile禁止指令重排序
    
    private DCLSingleton() {}
    
    public static DCLSingleton getInstance() {
        if (instance == null) {                    // 第一次检查
            synchronized (DCLSingleton.class) {    // 锁粒度控制
                if (instance == null) {            // 第二次检查
                    instance = new DCLSingleton();  // 安全发布
                }
            }
        }
        return instance;
    }
}

// 3. 枚举实现(《Effective Java》推荐方式)
public enum EnumSingleton {
    INSTANCE;
    public void businessMethod() { /*...*/ }
}

技术深挖

  1. volatile关键字:防止JVM指令重排序导致对象未初始化完成就被使用(JVM规范允许的优化)

  2. 类加载机制:枚举实现利用类加载的线程安全性保证单例

  3. 序列化攻击防御:枚举天然防反射和序列化破坏,普通实现需重写readResolve()

典型应用场景

// Java原生API中的单例
Runtime runtime = Runtime.getRuntime();      // JVM运行时环境单例
Desktop desktop = Desktop.getDesktop();     // 桌面操作单例

2. 工厂模式(Factory)——对象创建的工业化革命

模式演进三阶段
简单工厂 → 工厂方法 → 抽象工厂

工厂方法模式(Factory Method)
// 产品接口
public interface DatabaseConnection {
    void connect();
}

// 具体产品
public class MySQLConnection implements DatabaseConnection {
    @Override public void connect() { System.out.println("MySQL connected"); }
}

// 抽象工厂
public abstract class ConnectionFactory {
    public abstract DatabaseConnection createConnection();
    
    // 模板方法
    public void initializeConnection() {
        DatabaseConnection conn = createConnection();
        conn.connect();
        // 公共初始化逻辑...
    }
}

// 具体工厂
public class MySQLFactory extends ConnectionFactory {
    @Override
    public DatabaseConnection createConnection() {
        return new MySQLConnection();
    }
}

Spring框架中的高级应用

<!-- Bean配置工厂方法 -->
<bean id="mysqlFactory" class="com.example.MySQLFactory"/>
<bean id="connection" factory-bean="mysqlFactory" factory-method="createConnection"/>

三、结构型模式实战精讲

1. 适配器模式(Adapter)——接口转换的艺术

两种实现方式对比

类型实现方式适用场景Java示例
类适配器继承被适配类需要复用现有类代码较少使用
对象适配器组合被适配对象更灵活的解耦方式InputStreamReader

JDK中的经典实现

// 将字节流转换为字符流
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

现代Java中的函数式适配

// 使用Lambda适配旧接口
Runnable legacyTask = () -> System.out.println("Old task");
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(legacyTask::run);

2. 装饰器模式(Decorator)——动态增强的利器

模式结构

          Component
            ↑   ↑
        ConcreteComponent ← Decorator
                               ↑
                     ConcreteDecoratorA

Java IO流的装饰器体系

// 多层装饰示例
InputStream in = new FileInputStream("data.txt");
in = new BufferedInputStream(in);          // 添加缓冲功能
in = new GZIPInputStream(in);              // 添加压缩解压功能

自定义装饰器实现

public class CryptoInputStream extends FilterInputStream {
    private Cipher cipher;

    public CryptoInputStream(InputStream in, SecretKey key) throws GeneralSecurityException {
        super(in);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int bytesRead = super.read(b, off, len);
        if (bytesRead > 0) {
            try {
                cipher.doFinal(b, off, bytesRead);  // 解密处理
            } catch (IllegalBlockSizeException | BadPaddingException e) {
                throw new IOException("Decryption failed", e);
            }
        }
        return bytesRead;
    }
}

四、行为型模式核心剖析

1. 观察者模式(Observer)——事件驱动的基石

Java内置实现演进

// 传统实现(已过时但仍有参考价值)
public class Observable {
    private boolean changed = false;
    private Vector<Observer> observers;

    public synchronized void addObserver(Observer o) { /*...*/ }
    public void notifyObservers(Object arg) {
        // 同步通知逻辑...
    }
}

// 现代实现(推荐)
public class PropertyChangeSupport {
    public void addPropertyChangeListener(PropertyChangeListener listener) { /*...*/ }
    public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
        // 事件派发...
    }
}

响应式编程扩展(RxJava示例):

Observable<String> observable = Observable.create(emitter -> {
    emitter.onNext("Event 1");
    emitter.onNext("Event 2");
    emitter.onComplete();
});

observable.subscribe(
    event -> System.out.println("Received: " + event),
    error -> System.err.println("Error: " + error),
    () -> System.out.println("Completed")
);

2. 策略模式(Strategy)——算法族的自由切换

Lambda表达式带来的革新

// 传统实现
public interface ValidationStrategy {
    boolean execute(String s);
}

public class IsNumeric implements ValidationStrategy {
    @Override
    public boolean execute(String s) {
        return s.matches("\\d+");
    }
}

// Lambda实现
ValidationStrategy numericStrategy = s -> s.matches("\\d+");
ValidationStrategy lowerCaseStrategy = s -> s.matches("[a-z]+");

// 上下文使用
public class Validator {
    private ValidationStrategy strategy;
    
    public Validator(ValidationStrategy v) { this.strategy = v; }
    
    public boolean validate(String s) { return strategy.execute(s); }
}

Java集合框架的典型应用

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Collections.sort(names, (a, b) -> b.compareTo(a));  // 策略注入

五、Java特有模式深度探讨

1. 空对象模式(Null Object)——防御式编程的优雅解决方案

完整实现示例

public interface Logger {
    void log(String message);
}

public class ConsoleLogger implements Logger {
    @Override
    public void log(String message) {
        System.out.println(message);
    }
}

public class NullLogger implements Logger {
    @Override
    public void log(String message) {
        // 静默处理
    }
}

// 客户端使用
public class PaymentService {
    private Logger logger = new NullLogger();  // 默认安全
    
    public void setLogger(Logger logger) {
        this.logger = Objects.requireNonNullElse(logger, new NullLogger());
    }
    
    public void processPayment() {
        logger.log("Payment started");
        // 业务逻辑...
    }
}

2. 不可变对象模式(Immutable Object)——并发安全的终极形态

构建不可变类的五大铁律

  1. 所有字段final修饰
  2. 类声明为final
  3. 不暴露可变引用
  4. 不提供setter方法
  5. 构造器完全初始化

深度防御示例

public final class ImmutablePerson {
    private final String name;
    private final Date birthDate;  // Date本身可变
    
    public ImmutablePerson(String name, Date birthDate) {
        this.name = name;
        // 防御性拷贝
        this.birthDate = new Date(birthDate.getTime());
    }
    
    public Date getBirthDate() {
        // 返回拷贝对象
        return new Date(birthDate.getTime());
    }
}

六、模式应用黄金法则

1. 模式选择决策树

是否需要控制对象创建? → 创建型模式
    ├─ 需要全局唯一实例 → 单例
    ├─ 需要复杂构造过程 → 建造者
    └─ 需要灵活的产品族 → 抽象工厂

是否需要重组对象结构? → 结构型模式
    ├─ 接口不兼容 → 适配器
    ├─ 需要透明扩展 → 装饰器
    └─ 控制对象访问 → 代理

是否需要协调对象行为? → 行为型模式
    ├─ 事件通知机制 → 观察者
    ├─ 算法动态切换 → 策略
    └─ 流程标准化 → 模板方法

2. 模式反模式警示

  • 单例滥用:导致隐藏的依赖关系和测试困难
  • 过度装饰:产生过多小对象影响性能
  • 观察者泄漏:未及时取消注册导致内存泄漏
  • 策略膨胀:大量策略类增加维护成本

七、现代Java中的模式演进

1. Lambda表达式对传统模式的冲击

策略模式简化

// 传统方式
Arrays.sort(words, new Comparator<String>() {
    public int compare(String a, String b) {
        return Integer.compare(a.length(), b.length());
    }
});

// Lambda简化
Arrays.sort(words, (a, b) -> Integer.compare(a.length(), b.length()));

2. 模块化带来的模式变化

服务加载器替代工厂模式

// META-INF/services/com.example.DatabaseConnection
ServiceLoader<DatabaseConnection> loader = ServiceLoader.load(DatabaseConnection.class);
DatabaseConnection conn = loader.findFirst().orElseThrow();

八、设计模式在Java生态中的典型应用

框架/库核心模式具体实现
Spring工厂模式、代理模式、模板方法BeanFactory、AOP代理、JdbcTemplate
Hibernate代理模式、工厂模式延迟加载代理、SessionFactory
JavaFX观察者模式、命令模式Property绑定、EventHandler
Netty责任链模式、Reactor模式ChannelPipeline、EventLoop

相关文章:

  • linux DNS域名解析服务
  • 【AI应用】内容总结转成思维导图图片
  • uni-app app 安卓和ios防截屏
  • HTTP Content-Type:深入解析与应用
  • LeetCode算法题(Go语言实现)_37
  • 化工企业数字化转型:从数据贯通到生态重构的实践路径
  • vue 入门:组件事件
  • 备战蓝桥杯(非专业C++版)
  • 蓝桥杯 拼数(字符串大小比较)
  • 9.访问数据库2
  • 一个插件,免费使用所有顶级大模型(Deepseek,Gpt,Grok,Gemini)
  • 设计模式:抽象工厂 - 掌控多产品族的创建之道
  • # 实时人脸性别与年龄识别:基于OpenCV与深度学习模型的实现
  • Elasticsearch 超详细教程:从入门到精通
  • 《Uniapp-Vue 3-TS 实战开发:从入门到精通》专栏介绍
  • 15. git remote
  • 加密相关的知识点
  • 人-AI-环境系统智能赋能工程项目管理
  • 算法系列——无监督学习——13.LDA
  • 在 Windows 上安装 WSL Ubuntu 的完整避坑指南:从报错到成功运行
  • 长沙城乡建设网站首页/google play三件套
  • VM2008 做网站/百度一下你就知道手机版
  • 在线营销型网站制作/免费网页代码大全
  • dw外部网站链接怎么做/大数据精准营销的策略
  • wordpress 分类 输出/百度seo效果
  • 门户网站集约化建设/百度服务热线电话