Spring中都应用了哪些设计模式?

好的!以下是您提到的八种设计模式在 Spring 中的简单示例:

1. 简单工厂模式

简单工厂模式通过传入参数来决定实例化哪个类。Spring 中的 BeanFactory 就是简单工厂模式的应用。

示例代码:
// 1. 创建接口和具体实现类
public interface Animal {void speak();
}public class Dog implements Animal {@Overridepublic void speak() {System.out.println("Woof!");}
}public class Cat implements Animal {@Overridepublic void speak() {System.out.println("Meow!");}
}// 2. 工厂类,传入参数决定实例化哪个类
public class AnimalFactory {public static Animal getAnimal(String animalType) {if ("dog".equalsIgnoreCase(animalType)) {return new Dog();} else if ("cat".equalsIgnoreCase(animalType)) {return new Cat();}return null;}
}// 3. 使用工厂类创建实例
public class FactoryPatternDemo {public static void main(String[] args) {Animal dog = AnimalFactory.getAnimal("dog");dog.speak(); // 输出: Woof!Animal cat = AnimalFactory.getAnimal("cat");cat.speak(); // 输出: Meow!}
}

2. 工厂方法模式

工厂方法模式定义一个方法用于创建对象,由子类决定实例化哪一个类。Spring 使用 FactoryBean 来实现这个模式。

示例代码:
// 1. 定义接口
public interface Product {void doSomething();
}// 2. 具体实现
public class ConcreteProductA implements Product {@Overridepublic void doSomething() {System.out.println("ConcreteProductA is doing something.");}
}// 3. 工厂方法
public abstract class Creator {public abstract Product factoryMethod();
}public class ConcreteCreatorA extends Creator {@Overridepublic Product factoryMethod() {return new ConcreteProductA();}
}// 4. 使用工厂方法
public class FactoryMethodDemo {public static void main(String[] args) {Creator creator = new ConcreteCreatorA();Product product = creator.factoryMethod();product.doSomething(); // 输出: ConcreteProductA is doing something.}
}

3. 单例模式

Spring 中的 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;}
}public class SingletonDemo {public static void main(String[] args) {Singleton singleton = Singleton.getInstance();System.out.println(singleton);}
}

4. 代理模式

Spring AOP 是通过代理模式来增强对象的功能。Spring 提供了 JDK 动态代理和 CGLIB 代理。

示例代码(使用 JDK 动态代理):
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;public interface Service {void serve();
}public class ServiceImpl implements Service {@Overridepublic void serve() {System.out.println("Service is serving...");}
}public class ProxyHandler implements InvocationHandler {private final Object target;public ProxyHandler(Object target) {this.target = target;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("Before method call...");Object result = method.invoke(target, args);System.out.println("After method call...");return result;}
}public class ProxyPatternDemo {public static void main(String[] args) {Service service = new ServiceImpl();Service proxy = (Service) Proxy.newProxyInstance(Service.class.getClassLoader(),new Class[]{Service.class},new ProxyHandler(service));proxy.serve(); // 输出: Before method call... Service is serving... After method call...}
}

5. 装饰器模式

装饰器模式动态地给一个对象添加一些额外的功能。Spring 中的 DataSource 装饰模式就是这个例子。

示例代码:
public interface Coffee {String make();
}public class SimpleCoffee implements Coffee {@Overridepublic String make() {return "Simple Coffee";}
}public class MilkDecorator implements Coffee {private final Coffee coffee;public MilkDecorator(Coffee coffee) {this.coffee = coffee;}@Overridepublic String make() {return coffee.make() + " + Milk";}
}public class SugarDecorator implements Coffee {private final Coffee coffee;public SugarDecorator(Coffee coffee) {this.coffee = coffee;}@Overridepublic String make() {return coffee.make() + " + Sugar";}
}public class DecoratorPatternDemo {public static void main(String[] args) {Coffee coffee = new SimpleCoffee();System.out.println(coffee.make()); // 输出: Simple Coffeecoffee = new MilkDecorator(coffee);System.out.println(coffee.make()); // 输出: Simple Coffee + Milkcoffee = new SugarDecorator(coffee);System.out.println(coffee.make()); // 输出: Simple Coffee + Milk + Sugar}
}

6. 观察者模式

观察者模式用于一对多的依赖关系,Spring 中的事件监听器使用了这个模式。

示例代码:
import java.util.ArrayList;
import java.util.List;interface Observer {void update(String message);
}class ConcreteObserver implements Observer {private String name;public ConcreteObserver(String name) {this.name = name;}@Overridepublic void update(String message) {System.out.println(name + " received message: " + message);}
}class Subject {private List<Observer> observers = new ArrayList<>();public void addObserver(Observer observer) {observers.add(observer);}public void removeObserver(Observer observer) {observers.remove(observer);}public void notifyObservers(String message) {for (Observer observer : observers) {observer.update(message);}}
}public class ObserverPatternDemo {public static void main(String[] args) {Subject subject = new Subject();Observer observer1 = new ConcreteObserver("Observer 1");Observer observer2 = new ConcreteObserver("Observer 2");subject.addObserver(observer1);subject.addObserver(observer2);subject.notifyObservers("Hello Observers!"); // 输出: Observer 1 received message: Hello Observers!// 输出: Observer 2 received message: Hello Observers!}
}

7. 策略模式

策略模式允许在运行时选择算法。Spring 中的 HandlerMapping 使用了策略模式来根据请求映射到不同的处理器。

示例代码:
interface Strategy {void execute();
}class ConcreteStrategyA implements Strategy {@Overridepublic void execute() {System.out.println("Executing Strategy A");}
}class ConcreteStrategyB implements Strategy {@Overridepublic void execute() {System.out.println("Executing Strategy B");}
}class Context {private final Strategy strategy;public Context(Strategy strategy) {this.strategy = strategy;}public void executeStrategy() {strategy.execute();}
}public class StrategyPatternDemo {public static void main(String[] args) {Context contextA = new Context(new ConcreteStrategyA());contextA.executeStrategy(); // 输出: Executing Strategy AContext contextB = new Context(new ConcreteStrategyB());contextB.executeStrategy(); // 输出: Executing Strategy B}
}

8. 模板方法模式

模板方法模式定义了一个操作中的步骤,并允许子类在不改变操作结构的情况下实现某些步骤。

示例代码:
abstract class AbstractTemplate {public void templateMethod() {step1();step2();}protected abstract void step1();protected abstract void step2();
}class ConcreteClass extends AbstractTemplate {@Overrideprotected void step1() {System.out.println("Step 1");}@Overrideprotected void step2() {System.out.println("Step 2");}
}public class TemplateMethodPatternDemo {public static void main(String[] args) {AbstractTemplate template = new ConcreteClass();template.templateMethod();}
}

以上示例演示了 Spring 中常见的 8 种设计模式的应用。通过这些设计模式,Spring 提供了高度的灵活性和可扩展性,帮助开发者实现松耦合和高内聚的代码结构。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/69667.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Oracle专栏】本地 expdp 导出远程库

Oracle相关文档,希望互相学习,共同进步 风123456789~-CSDN博客 1.背景 近期需要在远程备份机器上远程导出数据库,之前用expdp数据泵只导出过本服务器的,本文跨服务器使用expdp 。 2. 测试 2.1 本机装完整oracle时,执行expdp导出远端数据库 实验说明:以下12为本机,14…

Flink KafkaConsumer offset是如何提交的

一、fllink 内部配置 client.id.prefix&#xff0c;指定用于 Kafka Consumer 的客户端 ID 前缀partition.discovery.interval.ms&#xff0c;定义 Kafka Source 检查新分区的时间间隔。 请参阅下面的动态分区检查一节register.consumer.metrics 指定是否在 Flink 中注册 Kafka…

【leetcode】双指针:移动零 and 复写零

文章目录 1.移动零2.复写零 1.移动零 class Solution { public:void moveZeroes(vector<int>& nums) {for (int cur 0, dest -1; cur < nums.size(); cur)if (nums[cur] ! 0)swap(nums[dest], nums[cur]);} };class Solution { public:void moveZeroes(vector&l…

网络安全工程师逆元计算 网络安全逆向

中职逆向题目整理合集 逆向分析&#xff1a;PE01.exe算法破解&#xff1a;flag0072算法破解&#xff1a;flag0073算法破解&#xff1a;CrackMe.exe远程代码执行渗透测试天津逆向re1 re22023江苏省re12023年江苏省赛re2_easygo.exe2022天津市PWN 逆向分析&#xff1a;PE01.exe …

string类(二)

目录 前言 string类的常用接口说明 3、string类对象的容量操作 3.1 size&#xff0c;length和capacity 3.2 empty和clear 3.3 reserve 3.4 resize 4、string类的修改操作 4.1 operator 4.2 c_str 4.3 findnpos 5、string类非成员函数 5.1 operator>>和opera…

医疗影响分割 | 使用 Swin UNETR 训练自己的数据集(3D医疗影像分割教程)

<Swin UNETR: Swin Transformers for Semantic Segmentation of Brain Tumors in MRI Images> 代码地址:unetr 论文地址:https://arxiv.org/pdf/2201.01266 一、下载代码 在Github上下载代码,然后进入SWINUNETR,前两个是针对两个数据集(BRATS21、BTCV)的操作,这里…

在CAD中插入图块后为什么看不到?怎么解决?

按照正确操作插入图块&#xff0c;但图纸上不显示新插入的图块&#xff0c;这是为什么&#xff1f; 原因可能是大家插入的图块太小&#xff0c;导致看不到&#xff0c;显示成一个点&#xff0c;所以大家插入图块的时候记得根据图纸大小&#xff0c;将比例改大一些就可以啦✌️…

【CMAEL多智能体框架】第一节 环境搭建及简单应用(构建一个鲜花选购智能体)

第一节 环境搭建 文章目录 第一节 环境搭建前言一、安装二、获取API1. 使用熟悉的API代理平台2.设置不使用明文存放API 三 、具体应用进阶任务 总结 前言 CAMEL Multi-Agent是一个开源的、灵活的框架&#xff0c;它提供了一套完整的工具和库&#xff0c;用于构建和模拟多智能体…

Flink-序列化

一、概述 几乎每个Flink作业都必须在其运算符之间交换数据&#xff0c;由于这些记录不仅可以发送到同一JVM中的另一个实例&#xff0c;还可以发送到单独的进程&#xff0c;因此需要先将记录序列化为字节。类似地&#xff0c;Flink的堆外状态后端基于本地嵌入式RocksDB实例&…

使用DeepSeek和Kimi快速自动生成PPT

目录 步骤1&#xff1a;在DeepSeek中生成要制作的PPT主要大纲内容。 &#xff08;1&#xff09;在DeepSeek网页端生成 &#xff08;2&#xff09;在本地部署DeepSeek后&#xff0c;使用chatBox生成PPT内容 步骤2&#xff1a;将DeepSeek成的PPT内容复制到Kimi中 步骤3&…

第41天:Web开发-JS应用微信小程序源码架构编译预览逆向调试嵌套资产代码审计

#知识点 1、安全开发-微信小程序-搭建&开发&架构&安全 2、安全开发-微信小程序-编译调试&反编译&泄露 一、小程序创建&#xff08;了解即可&#xff09; 1、下载微信开发者工具 2、创建小程序模版引用 https://developers.weixin.qq.com/miniprogram/dev/d…

Arduino 第十一章:温度传感器

Arduino 第十一章&#xff1a;LM35 温度传感器 一、LM35 简介 LM35 是美国国家半导体公司&#xff08;现德州仪器&#xff09;生产的一款精密集成电路温度传感器。与基于热力学原理的传统温度传感器不同&#xff0c;LM35 能直接将温度转换为电压输出&#xff0c;且输出电压与…

Oracle常用导元数据方法

1 说明 前两天领导发邮件要求导出O库一批表和索引的ddl语句做国产化测试&#xff0c;涉及6个系统&#xff0c;6千多张表&#xff0c;还好涉及的用户并不多&#xff0c;要不然很麻烦。 如此大费周折原因&#xff0c;是某国产库无法做元数据迁移。。。额&#xff0c;只能我手动导…

2022java面试总结,1000道(集合+JVM+并发编程+Spring+Mybatis)的Java高频面试题

1、面试题模块汇总 面试题包括以下十九个模块&#xff1a; Java 基础、容器、多线程、反射、对象拷贝、Java Web 模块、异常、网络、设计模式、Spring/Spring MVC、Spring Boot/Spring Cloud、Hibernate、Mybatis、RabbitMQ、Kafka、Zookeeper、MySql、Redis、JVM 。如下图所示…

Curser2_解除机器码限制

# Curser1_无限白嫖试用次数 文末有所需工具下载地址 Cursor Device ID Changer 一个用于修改 Cursor 编辑器设备 ID 的跨平台工具集。当遇到设备 ID 锁定问题时&#xff0c;可用于重置设备标识。 功能特性 ✨ 支持 Windows 和 macOS 系统&#x1f504; 自动生成符合格式的…

carbon 加入 GitCode:Golang 时间处理的 “瑞士军刀”

在 Golang 的开发生态中&#xff0c;时间处理领域长期存在着诸多挑战。高效、精准的时间处理对于各类软件应用的稳定运行与功能拓展至关重要。近日&#xff0c;carbon 正式加入 GitCode&#xff0c;为 Golang 开发者带来一款强大且便捷的时间处理利器&#xff0c;助力项目开发迈…

算法学习--链表

引言&#xff1a;为什么进行链表的学习&#xff1f; 考察能力独特&#xff1a;链表能很好地考察应聘者对指针操作、内存管理的理解和运用能力&#xff0c;还能检验代码的鲁棒性&#xff0c;比如处理链表的插入、删除操作时对边界条件的处理。数据结构基础&#xff1a;链表是很多…

域名劫持原理与实践

了解域名及域名劫持 由于点分十进制的IP地址难于记忆&#xff0c;便出现了域名。由于网络传输中最终还是基于IP&#xff0c;所以必须通过一种机制将IP和域名一一对应起来&#xff0c;这便是DNS。全球总共有13台根域名服务器。 域名劫持是互联网攻击中常见的一种攻击方式&…

【论文翻译】DeepSeek-V3论文翻译——DeepSeek-V3 Technical Report——第二部分:(训练硬件)基础设施

论文原文链接&#xff1a;DeepSeek-V3/DeepSeek_V3.pdf at main deepseek-ai/DeepSeek-V3 GitHub 特别声明&#xff0c;本文不做任何商业用途&#xff0c;仅作为个人学习相关论文的翻译记录。本文对原文内容直译&#xff0c;一切以论文原文内容为准&#xff0c;对原文作者表示…

MapReduce到底是个啥?

在聊 MapReduce 之前不妨先看个例子&#xff1a;假设某短视频平台日活用户大约在7000万左右&#xff0c;若平均每一个用户产生3条行为日志&#xff1a;点赞、转发、收藏&#xff1b;这样就是两亿条行为日志&#xff0c;再假设每条日志大小为100个字节&#xff0c;那么一天就会产…