👉 这是一个或许对你有用的社群
🐱 一对一交流/面试小册/简历优化/求职解惑,欢迎加入「芋道快速开发平台」知识星球。下面是星球提供的部分资料:
《项目实战(视频)》:从书中学,往事上“练”
《互联网高频面试题》:面朝简历学习,春暖花开
《架构 x 系统设计》:摧枯拉朽,掌控面试高频场景题
《精进 Java 学习指南》:系统学习,互联网主流技术栈
《必读 Java 源码专栏》:知其然,知其所以然

👉这是一个或许对你有用的开源项目
国产 Star 破 10w+ 的开源项目,前端包括管理后台 + 微信小程序,后端支持单体和微服务架构。
功能涵盖 RBAC 权限、SaaS 多租户、数据权限、商城、支付、工作流、大屏报表、微信公众号、ERP、CRM、AI 大模型等等功能:
Boot 多模块架构:https://gitee.com/zhijiantianya/ruoyi-vue-pro
Cloud 微服务架构:https://gitee.com/zhijiantianya/yudao-cloud
视频教程:https://doc.iocoder.cn
【国内首批】支持 JDK 17/21 + SpringBoot 3.3、JDK 8/11 + Spring Boot 2.7 双版本

前言
设计模式在我们日常的软件开发中无处不在,它们帮助我们编写更易扩展、更具可读性的代码。
今天结合我实际工作场景和源码实例,跟大家一起聊聊工作中最常用的8种设计模式,希望对你会有所帮助。
基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能
项目地址:https://github.com/YunaiV/ruoyi-vue-pro
视频教程:https://doc.iocoder.cn/video/
1. 单例模式
单例模式确保一个类只有一个实例,通常用于管理共享资源,如配置、缓存、线程池等。
代码实现:双重检查锁这是单例模式的标准写法,既保证线程安全,又避免性能损耗。
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;
}
}
JDK 中的应用:
java.lang.Runtime.getRuntime()java.util.logging.Logger
Spring 中的应用:Spring 的 Bean 默认是单例模式。可以通过 @Scope("prototype") 将其改为多例。
基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能
项目地址:https://github.com/YunaiV/yudao-cloud
视频教程:https://doc.iocoder.cn/video/
2. 工厂模式
工厂模式用于封装对象的创建逻辑,特别是当类实例化过程复杂时,可以降低耦合度。
代码实现:简单工厂以支付系统为例,不同支付方式需要不同的对象。
public class PaymentFactory {
public static Payment createPayment(String type) {
switch (type) {
case "AliPay":
return new AliPay();
case "WeChatPay":
return new WeChatPay();
default:
throw new IllegalArgumentException("Unknown payment type");
}
}
}
JDK 中的应用:
java.util.Calendar.getInstance()javax.xml.parsers.DocumentBuilderFactory.newInstance()
Spring 中的应用:
BeanFactory和ApplicationContext都是工厂模式的体现。
3. 策略模式
策略模式将不同算法封装为独立类,并允许在运行时选择不同的策略。
代码实现:促销策略以电商促销为例,支持满减、打折等多种策略。
public interface PromotionStrategy {
void applyPromotion();
}
public class DiscountStrategy implements PromotionStrategy {
@Override
public void applyPromotion() {
System.out.println("Applying discount...");
}
}
public class PromotionContext {
private PromotionStrategy strategy;
public PromotionContext(PromotionStrategy strategy) {
this.strategy = strategy;
}
public void executePromotion() {
strategy.applyPromotion();
}
}
JDK 中的应用:
java.util.Comparator是典型的策略模式。
Spring 中的应用:
事务管理(
TransactionManager),支持编程式和声明式事务。
4. 代理模式
代理模式通过代理对象控制对目标对象的访问,常用于权限控制、日志记录等场景。
代码实现:静态代理模拟对一个服务的权限控制。
public interface Service {
void execute();
}
public class RealService implements Service {
@Override
public void execute() {
System.out.println("Executing real service...");
}
}
public class ServiceProxy implements Service {
private RealService realService;
@Override
public void execute() {
System.out.println("Checking permissions...");
if (realService == null) {
realService = new RealService();
}
realService.execute();
}
}
JDK 中的应用:
动态代理
java.lang.reflect.ProxyRMI(远程方法调用)
Spring 中的应用:
AOP(面向切面编程)广泛使用代理模式。
5. 观察者模式
观察者模式定义一对多的依赖,当一个对象状态变化时,所有依赖它的对象都会收到通知。
代码实现:事件通知模拟微博用户的粉丝通知。
public interface Observer {
void update(String message);
}
public class User implements Observer {
private String name;
public User(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + " received message: " + message);
}
}
public class Weibo {
private List<Observer> observers = new ArrayList<>();
public void follow(Observer observer) {
observers.add(observer);
}
public void post(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
JDK 中的应用:
java.util.Observer和java.util.Observablejavax.swing.event.ChangeListener
Spring 中的应用:
ApplicationEvent和ApplicationListener是典型实现。
6. 装饰器模式
装饰器模式在不改变原始类的基础上,动态扩展其功能。
代码实现:咖啡加料模拟一个咖啡订单系统,可以动态加料。
public interface Coffee {
String getDescription();
double getCost();
}
public class SimpleCoffee implements Coffee {
@Override
public String getDescription() {
return "Simple Coffee";
}
@Override
public double getCost() {
return 5.0;
}
}
public class MilkDecorator implements Coffee {
private Coffee coffee;
public MilkDecorator(Coffee coffee) {
this.coffee = coffee;
}
@Override
public String getDescription() {
return coffee.getDescription() + ", Milk";
}
@Override
public double getCost() {
return coffee.getCost() + 1.5;
}
}
JDK 中的应用:
java.io.BufferedInputStream和java.io.BufferedOutputStream
Spring 中的应用:
BeanPostProcessor用于动态修改 Bean 的行为。
7. 模板方法模式
模板方法模式定义一个算法的骨架,把具体的实现留给子类。
代码实现:任务执行模板模拟定时任务的执行流程。
public abstract class Task {
public final void execute() {
init();
doWork();
cleanup();
}
protected abstract void init();
protected abstract void doWork();
protected void cleanup() {
System.out.println("Default cleanup...");
}
}
public class DataProcessingTask extends Task {
@Override
protected void init() {
System.out.println("Initializing data...");
}
@Override
protected void doWork() {
System.out.println("Processing data...");
}
}
JDK 中的应用:
java.util.AbstractList和java.util.AbstractMap
Spring 中的应用:
JdbcTemplate和RestTemplate
8. 建造者模式
建造者模式用于创建复杂对象,特别是当对象有多个可选参数时。
代码实现:构建 HTTP 请求
public class HttpRequest {
private String method;
private String url;
private String body;
private HttpRequest(Builder builder) {
this.method = builder.method;
this.url = builder.url;
this.body = builder.body;
}
public static class Builder {
private String method;
private String url;
private String body;
public Builder method(String method) {
this.method = method;
return this;
}
public Builder url(String url) {
this.url = url;
return this;
}
public Builder body(String body) {
this.body = body;
return this;
}
public HttpRequest build() {
return new HttpRequest(this);
}
}
}
JDK 中的应用:
StringBuilderStream.Builder
Spring 中的应用:
UriComponentsBuilder用于构建 URI。
总结
这些设计模式不仅在日常开发中有着广泛应用,更在 JDK 和 Spring 中深度体现。
了解它们的本质和应用场景,能够让我们写出更优雅、更健壮的代码。
下次再遇到类似问题时,希望你能得心应手地选择合适的模式!
欢迎加入我的知识星球,全面提升技术能力。
👉 加入方式,“长按”或“扫描”下方二维码噢:

星球的内容包括:项目实战、面试招聘、源码解析、学习路线。





文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*)
1万+



被折叠的 条评论
为什么被折叠?



