news 2026/1/31 6:16:20

Java设计模式应用实战:提升代码质量的23种经典解决方案_java业务开发中简单实用的设计模式,零基础入门到精通,收藏这篇就够了

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Java设计模式应用实战:提升代码质量的23种经典解决方案_java业务开发中简单实用的设计模式,零基础入门到精通,收藏这篇就够了

设计模式是软件工程中的智慧结晶,是解决特定问题的最佳实践模板。本文通过真实项目场景和代码示例,深入解析23种设计模式在Java开发中的实战应用,助你写出更优雅、更健壮的代码。

一、设计模式基础:为什么需要模式?

设计模式的三大分类
分类核心目的常用模式
创建型对象创建过程的抽象工厂方法、抽象工厂、单例、建造者、原型
结构型类和对象组合的方式适配器、装饰器、代理、外观、组合、享元
行为型对象间的通信与职责分配策略、观察者、命令、状态、责任链、模板方法
设计模式的六大原则
  1. 开闭原则:对扩展开放,对修改关闭
  2. 里氏替换:子类可以替换父类
  3. 依赖倒置:面向接口编程,而非实现
  4. 接口隔离:多个专用接口优于单一通用接口
  5. 迪米特法则:减少对象间的耦合
  6. 单一职责:一个类只负责一个功能领域

二、创建型模式实战:优雅创建对象

1. 工厂方法模式(支付系统案例)
// 支付接口 public interface Payment { void pay(BigDecimal amount); } // 具体实现 public class Alipay implements Payment { public void pay(BigDecimal amount) { System.out.println("支付宝支付:" + amount); } } public class WechatPay implements Payment { public void pay(BigDecimal amount) { System.out.println("微信支付:" + amount); } } // 工厂接口 public interface PaymentFactory { Payment createPayment(); } // 具体工厂 public class AlipayFactory implements PaymentFactory { public Payment createPayment() { return new Alipay(); } } public class WechatPayFactory implements PaymentFactory { public Payment createPayment() { return new WechatPay(); } } // 使用 public class PaymentService { public void processPayment(PaymentFactory factory, BigDecimal amount) { Payment payment = factory.createPayment(); payment.pay(amount); } }

应用场景:支付渠道扩展、数据库连接池、日志系统

2. 建造者模式(复杂对象创建)
public class Computer { private String cpu; private String ram; private String ssd; // 私有构造器 private Computer(Builder builder) { this.cpu = builder.cpu; this.ram = builder.ram; this.ssd = builder.ssd; } public static class Builder { private String cpu; private String ram; private String ssd; public Builder cpu(String cpu) { this.cpu = cpu; return this; } public Builder ram(String ram) { this.ram = ram; return this; } public Builder ssd(String ssd) { this.ssd = ssd; return this; } public Computer build() { return new Computer(this); } } } // 使用 Computer gamingPC = new Computer.Builder() .cpu("Intel i9") .ram("32GB DDR5") .ssd("1TB NVMe") .build();

应用场景:配置对象创建、HTTP请求构造、SQL查询构建

三、结构型模式实战:灵活组合对象

1. 适配器模式(第三方服务集成)
// 目标接口 public interface CloudStorage { void uploadFile(String fileName); void downloadFile(String fileName); } // 第三方服务(不兼容接口) public class AWSS3Service { public void putObject(String key) { System.out.println("AWS S3 上传: " + key); } public void getObject(String key) { System.out.println("AWS S3 下载: " + key); } } // 适配器 public class S3Adapter implements CloudStorage { private AWSS3Service s3Service; public S3Adapter(AWSS3Service s3Service) { this.s3Service = s3Service; } public void uploadFile(String fileName) { s3Service.putObject(fileName); } public void downloadFile(String fileName) { s3Service.getObject(fileName); } } // 使用 CloudStorage storage = new S3Adapter(new AWSS3Service()); storage.uploadFile("report.pdf");

应用场景:旧系统整合、API兼容、设备驱动

2. 装饰器模式(Java IO扩展)
// 基础组件 public interface DataSource { void writeData(String data); String readData(); } // 具体组件 public class FileDataSource implements DataSource { private String filename; public FileDataSource(String filename) { this.filename = filename; } public void writeData(String data) { System.out.println("写入文件: " + data); } public String readData() { return "文件数据"; } } // 装饰器基类 public abstract class DataSourceDecorator implements DataSource { protected DataSource wrappee; public DataSourceDecorator(DataSource source) { this.wrappee = source; } } // 具体装饰器:加密 public class EncryptionDecorator extends DataSourceDecorator { public EncryptionDecorator(DataSource source) { super(source); } public void writeData(String data) { String encrypted = encrypt(data); wrappee.writeData(encrypted); } public String readData() { String data = wrappee.readData(); return decrypt(data); } private String encrypt(String data) { return "加密(" + data + ")"; } private String decrypt(String data) { return data.substring(3, data.length() - 1); } } // 使用 DataSource source = new EncryptionDecorator( new FileDataSource("data.txt") ); source.writeData("敏感信息"); // 写入: 加密(敏感信息)

应用场景:Java IO流、Spring Security过滤器链、GUI组件增强

四、行为型模式实战:高效对象协作

1. 策略模式(电商促销系统)
// 策略接口 public interface DiscountStrategy { BigDecimal applyDiscount(BigDecimal amount); } // 具体策略 public class NoDiscount implements DiscountStrategy { public BigDecimal applyDiscount(BigDecimal amount) { return amount; } } public class PercentageDiscount implements DiscountStrategy { private BigDecimal percentage; public PercentageDiscount(BigDecimal percentage) { this.percentage = percentage; } public BigDecimal applyDiscount(BigDecimal amount) { return amount.multiply(BigDecimal.ONE.subtract(percentage)); } } public class FixedDiscount implements DiscountStrategy { private BigDecimal discountAmount; public FixedDiscount(BigDecimal discountAmount) { this.discountAmount = discountAmount; } public BigDecimal applyDiscount(BigDecimal amount) { return amount.subtract(discountAmount); } } // 上下文 public class Order { private BigDecimal amount; private DiscountStrategy discountStrategy = new NoDiscount(); public void setDiscountStrategy(DiscountStrategy strategy) { this.discountStrategy = strategy; } public BigDecimal calculateTotal() { return discountStrategy.applyDiscount(amount); } } // 使用 Order order = new Order(); order.setAmount(new BigDecimal("100")); // 双11活动:75折 order.setDiscountStrategy(new PercentageDiscount(new BigDecimal("0.25"))); System.out.println("折扣价: " + order.calculateTotal()); // 75.00 // 会员日:满100减20 order.setDiscountStrategy(new FixedDiscount(new BigDecimal("20"))); System.out.println("折扣价: " + order.calculateTotal()); // 80.00

应用场景:支付方式选择、排序算法切换、游戏AI行为

2. 观察者模式(事件通知系统)
// 观察者接口 public interface EventListener { void update(String eventType, File file); } // 被观察对象 public class EventManager { private Map<String, List<EventListener>> listeners = new HashMap<>(); public EventManager(String... operations) { for (String operation : operations) { listeners.put(operation, new ArrayList<>()); } } public void subscribe(String eventType, EventListener listener) { listeners.get(eventType).add(listener); } public void unsubscribe(String eventType, EventListener listener) { listeners.get(eventType).remove(listener); } public void notify(String eventType, File file) { for (EventListener listener : listeners.get(eventType)) { listener.update(eventType, file); } } } // 具体被观察者 public class Editor { public EventManager events; private File file; public Editor() { events = new EventManager("open", "save"); } public void openFile(String path) { this.file = new File(path); events.notify("open", file); } public void saveFile() { if (file != null) { events.notify("save", file); } } } // 具体观察者 public class EmailNotificationListener implements EventListener { private String email; public EmailNotificationListener(String email) { this.email = email; } public void update(String eventType, File file) { System.out.println("邮件通知: " + email + " 文件 " + file.getName() + " 执行了 " + eventType + " 操作"); } } // 使用 Editor editor = new Editor(); editor.events.subscribe("open", new EmailNotificationListener("admin@example.com")); editor.events.subscribe("save", new EmailNotificationListener("admin@example.com")); editor.openFile("test.txt"); editor.saveFile();

应用场景:消息队列消费者、GUI事件处理、微服务状态同步

五、综合应用:电商系统中的设计模式组合

架构设计图

#mermaid-svg-RTk3H4OEggE2B4An {font-family:“trebuchet ms”,verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-RTk3H4OEggE2B4An .error-icon{fill:#552222;}#mermaid-svg-RTk3H4OEggE2B4An .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-RTk3H4OEggE2B4An .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-RTk3H4OEggE2B4An .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-RTk3H4OEggE2B4An .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-RTk3H4OEggE2B4An .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-RTk3H4OEggE2B4An .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-RTk3H4OEggE2B4An .marker{fill:#333333;stroke:#333333;}#mermaid-svg-RTk3H4OEggE2B4An .marker.cross{stroke:#333333;}#mermaid-svg-RTk3H4OEggE2B4An svg{font-family:“trebuchet ms”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-RTk3H4OEggE2B4An .label{font-family:“trebuchet ms”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-RTk3H4OEggE2B4An .cluster-label text{fill:#333;}#mermaid-svg-RTk3H4OEggE2B4An .cluster-label span{color:#333;}#mermaid-svg-RTk3H4OEggE2B4An .label text,#mermaid-svg-RTk3H4OEggE2B4An span{fill:#333;color:#333;}#mermaid-svg-RTk3H4OEggE2B4An .node rect,#mermaid-svg-RTk3H4OEggE2B4An .node circle,#mermaid-svg-RTk3H4OEggE2B4An .node ellipse,#mermaid-svg-RTk3H4OEggE2B4An .node polygon,#mermaid-svg-RTk3H4OEggE2B4An .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-RTk3H4OEggE2B4An .node .label{text-align:center;}#mermaid-svg-RTk3H4OEggE2B4An .node.clickable{cursor:pointer;}#mermaid-svg-RTk3H4OEggE2B4An .arrowheadPath{fill:#333333;}#mermaid-svg-RTk3H4OEggE2B4An .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-RTk3H4OEggE2B4An .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-RTk3H4OEggE2B4An .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-RTk3H4OEggE2B4An .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-RTk3H4OEggE2B4An .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-RTk3H4OEggE2B4An .cluster text{fill:#333;}#mermaid-svg-RTk3H4OEggE2B4An .cluster span{color:#333;}#mermaid-svg-RTk3H4OEggE2B4An div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:“trebuchet ms”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-RTk3H4OEggE2B4An :root{–mermaid-font-family:“trebuchet ms”,verdana,arial,sans-serif;}

客户端

外观模式 Facade

订单子系统

支付子系统

库存子系统

工厂模式 OrderFactory

建造者模式 OrderBuilder

策略模式 PaymentStrategy

代理模式 PaymentProxy

观察者模式 StockObserver

状态模式 OrderState

核心代码实现
// 外观模式:统一入口 public class ECommerceFacade { private OrderService orderService; private PaymentService paymentService; private InventoryService inventoryService; public ECommerceFacade() { this.orderService = new OrderService(); this.paymentService = new PaymentService(); this.inventoryService = new InventoryService(); } public void placeOrder(OrderRequest request) { // 创建订单 Order order = orderService.createOrder(request); // 扣减库存 inventoryService.reduceStock(order); // 支付处理 paymentService.processPayment(order); // 状态通知 orderService.notifyStatus(order); } } // 状态模式:订单状态流转 public class Order { private OrderState state = new NewState(); public void setState(OrderState state) { this.state = state; } public void nextState() { state.next(this); } public void previousState() { state.previous(this); } } public interface OrderState { void next(Order order); void previous(Order order); } public class NewState implements OrderState { public void next(Order order) { order.setState(new ProcessingState()); } public void previous(Order order) { System.out.println("初始状态"); } } public class ProcessingState implements OrderState { public void next(Order order) { order.setState(new ShippedState()); } public void previous(Order order) { order.setState(new NewState()); } }

六、设计模式最佳实践与陷阱规避

1. 模式选择决策树
graph TD A[需要解决的问题] --> B{对象创建?} B -->|是| C[创建型模式] B -->|否| D{对象结构?} D -->|是| E[结构型模式] D -->|否| F{对象交互?} F -->|是| G[行为型模式] C --> C1{需要解耦?} C1 -->|是| C2[工厂/抽象工厂] C1 -->|否| C3{需要控制实例?} C3 -->|是| C4[单例] E --> E1{接口不兼容?} E1 -->|是| E2[适配器] E1 -->|否| E3{需要增强功能?} E3 -->|是| E4[装饰器] G --> G1{算法切换?} G1 -->|是| G2[策略] G1 -->|否| G3{事件通知?} G3 -->|是| G4[观察者]
2. 常见陷阱及解决方案
陷阱后果解决方案
单例滥用全局状态污染依赖注入替代全局访问
过度使用工厂代码复杂度增加仅在创建逻辑复杂时使用
装饰器嵌套过深调试困难限制装饰层数(建议<5层)
观察者循环通知栈溢出使用中介者模式协调
策略模式策略类膨胀类数量爆炸结合工厂方法管理策略
3. 现代Java中的模式演进

七、设计模式在开源框架中的应用

1. Spring框架中的设计模式
模式应用点实现类/注解
工厂方法Bean创建BeanFactory
代理模式AOP实现ProxyFactoryBean
模板方法JdbcTemplateJdbcTemplate
观察者模式事件机制ApplicationEvent
适配器模式MVC处理器适配HandlerAdapter
2. MyBatis框架中的设计模式
// 建造者模式:SqlSessionFactoryBuilder SqlSessionFactory factory = new SqlSessionFactoryBuilder() .build(inputStream); // 代理模式:Mapper接口代理 UserMapper mapper = session.getMapper(UserMapper.class); // 模板方法:Executor执行流程 public abstract class BaseExecutor implements Executor { public <E> List<E> query(...) { // 模板方法 return doQuery(...); } protected abstract <E> List<E> doQuery(...); }

八、如何避免过度设计

设计模式应用的"三不原则"
  1. 不要预设计:在明确需求变化点前避免提前抽象
  2. 不要为模式而模式:模式是手段而非目的
  3. 不要复杂化:简单方案能解决时不引入模式
何时应该引入设计模式?

“设计模式不是银弹,而是经验的总结。真正优秀的开发者知道何时使用模式,更知道何时不用。” —— Erich Gamma(《设计模式》作者)

结语:从模式使用者到创造者

设计模式的学习分为三个阶段:

  1. 认知阶段:识别代码中的模式应用
  2. 应用阶段:在合适场景主动应用模式
  3. 创造阶段:根据业务特点创新模式变体

通过本文的实战案例和场景分析,希望你能跨越从理论到实践的鸿沟,真正掌握设计模式的精髓,最终创造出适用于自己业务领域的专属模式!

Java开发的就业市场正在经历结构性调整,竞争日益激烈

传统纯业务开发岗位(如仅完成增删改查业务的后端工程师)的需求,特别是入门级岗位,正显著萎缩。随着企业技术需求升级,市场对Java人才的要求已从通用技能转向了更深入的领域经验(如云原生、微服务)或前沿的AI集成能力。这也导致岗位竞争加剧,在一、二线城市,求职者不仅面临技术内卷,还需应对学历与项目经验的高门槛。

大模型为核心的AI领域正展现出前所未有的就业热度与人才红利

2025年,AI相关新发岗位数量同比激增543%,单月增幅最高超过11倍,大模型算法工程师位居热门岗位前列。行业顶尖人才的供需严重失衡,议价能力极强,跳槽薪资涨幅可达30%-50%。值得注意的是,市场并非单纯青睐算法研究员,而是急需能将大模型能力落地于复杂业务系统的工程人才。这使得具备企业级架构思维和复杂系统整合经验的Java工程师,在向“Java+大模型”复合人才转型时拥有独特优势,成为企业竞相争夺的对象,其薪资天花板也远高于传统Java岗位。

说真的,这两年看着身边一个个搞Java、C++、前端、数据、架构的开始卷大模型,挺唏嘘的。大家最开始都是写接口、搞Spring Boot、连数据库、配Redis,稳稳当当过日子。

结果GPT、DeepSeek火了之后,整条线上的人都开始有点慌了,大家都在想:“我是不是要学大模型,不然这饭碗还能保多久?”

先给出最直接的答案:一定要把现有的技术和大模型结合起来,而不是抛弃你们现有技术!掌握AI能力的Java工程师比纯Java岗要吃香的多。

即使现在裁员、降薪、团队解散的比比皆是……但后续的趋势一定是AI应用落地!大模型方向才是实现职业升级、提升薪资待遇的绝佳机遇!

如何学习AGI大模型?

作为一名热心肠的互联网老兵,我决定把宝贵的AI知识分享给大家。 至于能学习到多少就看你的学习毅力和能力了 。我已将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

因篇幅有限,仅展示部分资料,需要点击下方链接即可前往获取

2025最新版CSDN大礼包:《AGI大模型学习资源包》免费分享**

一、2025最新大模型学习路线

一个明确的学习路线可以帮助新人了解从哪里开始,按照什么顺序学习,以及需要掌握哪些知识点。大模型领域涉及的知识点非常广泛,没有明确的学习路线可能会导致新人感到迷茫,不知道应该专注于哪些内容。

我们把学习路线分成L1到L4四个阶段,一步步带你从入门到进阶,从理论到实战。

L1级别:AI大模型时代的华丽登场

L1阶段:我们会去了解大模型的基础知识,以及大模型在各个行业的应用和分析;学习理解大模型的核心原理,关键技术,以及大模型应用场景;通过理论原理结合多个项目实战,从提示工程基础到提示工程进阶,掌握Prompt提示工程。

L2级别:AI大模型RAG应用开发工程

L2阶段是我们的AI大模型RAG应用开发工程,我们会去学习RAG检索增强生成:包括Naive RAG、Advanced-RAG以及RAG性能评估,还有GraphRAG在内的多个RAG热门项目的分析。

L3级别:大模型Agent应用架构进阶实践

L3阶段:大模型Agent应用架构进阶实现,我们会去学习LangChain、 LIamaIndex框架,也会学习到AutoGPT、 MetaGPT等多Agent系统,打造我们自己的Agent智能体;同时还可以学习到包括Coze、Dify在内的可视化工具的使用。

L4级别:大模型微调与私有化部署

L4阶段:大模型的微调和私有化部署,我们会更加深入的探讨Transformer架构,学习大模型的微调技术,利用DeepSpeed、Lamam Factory等工具快速进行模型微调;并通过Ollama、vLLM等推理部署框架,实现模型的快速部署。

整个大模型学习路线L1主要是对大模型的理论基础、生态以及提示词他的一个学习掌握;而L3 L4更多的是通过项目实战来掌握大模型的应用开发,针对以上大模型的学习路线我们也整理了对应的学习视频教程,和配套的学习资料。

二、大模型经典PDF书籍

书籍和学习文档资料是学习大模型过程中必不可少的,我们精选了一系列深入探讨大模型技术的书籍和学习文档,它们由领域内的顶尖专家撰写,内容全面、深入、详尽,为你学习大模型提供坚实的理论基础(书籍含电子版PDF)

三、大模型视频教程

对于很多自学或者没有基础的同学来说,书籍这些纯文字类的学习教材会觉得比较晦涩难以理解,因此,我们提供了丰富的大模型视频教程,以动态、形象的方式展示技术概念,帮助你更快、更轻松地掌握核心知识

四、大模型项目实战

学以致用,当你的理论知识积累到一定程度,就需要通过项目实战,在实际操作中检验和巩固你所学到的知识,同时为你找工作和职业发展打下坚实的基础。

五、大模型面试题

面试不仅是技术的较量,更需要充分的准备。

在你已经掌握了大模型技术之后,就需要开始准备面试,我们将提供精心整理的大模型面试题库,涵盖当前面试中可能遇到的各种技术问题,让你在面试中游刃有余。


因篇幅有限,仅展示部分资料,需要点击下方链接即可前往获取

2025最新版CSDN大礼包:《AGI大模型学习资源包》免费分享

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/1/30 7:05:25

颠覆级Windows界面改造神器:ExplorerPatcher零门槛定制指南

颠覆级Windows界面改造神器&#xff1a;ExplorerPatcher零门槛定制指南 【免费下载链接】ExplorerPatcher 提升Windows操作系统下的工作环境 项目地址: https://gitcode.com/GitHub_Trending/ex/ExplorerPatcher 当你厌倦了Windows 11千篇一律的界面布局&#xff0c;却苦…

作者头像 李华
网站建设 2026/1/30 5:12:43

智能去重提升文献管理效率:Zotero Duplicates Merger插件全攻略

智能去重提升文献管理效率&#xff1a;Zotero Duplicates Merger插件全攻略 【免费下载链接】ZoteroDuplicatesMerger A zotero plugin to automatically merge duplicate items 项目地址: https://gitcode.com/gh_mirrors/zo/ZoteroDuplicatesMerger 在学术研究与文献管…

作者头像 李华
网站建设 2026/1/30 5:41:23

IBM 7B轻量模型Granite-4.0-H-Tiny:企业级智能新助手

IBM 7B轻量模型Granite-4.0-H-Tiny&#xff1a;企业级智能新助手 【免费下载链接】granite-4.0-h-tiny 项目地址: https://ai.gitcode.com/hf_mirrors/ibm-granite/granite-4.0-h-tiny 导语&#xff1a;IBM推出70亿参数轻量级大语言模型Granite-4.0-H-Tiny&#xff0c;…

作者头像 李华
网站建设 2026/1/30 19:42:14

解锁百度网盘高速下载秘诀:3大核心功能实现零成本提速

解锁百度网盘高速下载秘诀&#xff1a;3大核心功能实现零成本提速 【免费下载链接】baidu-wangpan-parse 获取百度网盘分享文件的下载地址 项目地址: https://gitcode.com/gh_mirrors/ba/baidu-wangpan-parse 你是否遇到过深夜加班时&#xff0c;重要项目文件却因百度网…

作者头像 李华
网站建设 2026/1/31 3:55:51

Z-Image-Turbo_UI界面历史画廊会加入吗?开发进展

Z-Image-Turbo_UI界面历史画廊会加入吗&#xff1f;开发进展 发布时间&#xff1a;2025年12月30日 最近不少用户在社区和镜像评论区反复问同一个问题&#xff1a;“Z-Image-Turbo_UI 界面什么时候能加上历史画廊&#xff1f;”——不是“能不能加”&#xff0c;而是“什么时候…

作者头像 李华