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 提供了高度的灵活性和可扩展性,帮助开发者实现松耦合和高内聚的代码结构。
相关文章:
Spring中都应用了哪些设计模式?
好的!以下是您提到的八种设计模式在 Spring 中的简单示例: 1. 简单工厂模式 简单工厂模式通过传入参数来决定实例化哪个类。Spring 中的 BeanFactory 就是简单工厂模式的应用。 示例代码: // 1. 创建接口和具体实现类 public interface A…...
VSCode的安裝以及使用
c配置: 【MinGw-w64编译器套件】 https://blog.csdn.net/weixin_60915103/article/details/131617196?fromshareblogdetail&sharetypeblogdetail&sharerId131617196&sharereferPC&sharesourcem0_51662391&sharefromfrom_link Python配置: 【簡單ÿ…...
Datawhale 组队学习 Ollama教程 task1
一、Ollama 简介 比喻:Ollama 就像是一个“魔法箱子”,里面装满了各种大型语言模型(LLM)。你不需要懂复杂的魔法咒语(配置),只需要轻轻一按(一条命令),就能让…...
前端技术学习——ES6核心基础
1、ES6与JavaScript之间的关系 ES6是JavaScript的一个版本:JavaScript是基于ECMAScript规范实现的编程语言,而ES6(ECMAScript 2015)是该规范的一个具体版本。 2、ES6的基础功能 (1)let和const let用于声明…...
《DeepSeek技术应用与赋能运营商办公提效案例实操落地课程》
大模型算法实战专家—周红伟老师 法国科学院数据算法博士/曾任阿里巴巴人工智能专家/曾任马上消费企业风控负责人 课程背景 随着大模型技术的迅猛发展,企业面临着提升工作效率、降低运营成本和优化资源配置的巨大压力。DeepSeek做出十三项革命性的大模型技术突破…...
STM32-知识
一、Cortex-M系列双指针 Cortex-M系列的MSP与PSP有一些重要的区别,双指针是为了保证OS的安全性和稳健性。本质上,区别于用户程序使用PSP,操作系统和异常事件单独使用一个MSP指针的目的,是为了保证栈数据不会被用户程序意外访问或…...
线程同步(互斥锁与条件变量)
文章目录 1、为什么要用互斥锁2、互斥锁怎么用3、为什么要用条件变量4、互斥锁和条件变量如何配合使用5、互斥锁和条件变量的常见用法 参考资料:https://blog.csdn.net/m0_53539646/article/details/115509348 1、为什么要用互斥锁 为了使各线程能够有序地访问公共…...
Ubuntu指令学习(个人记录、偶尔更新)
Ubuntu指令学习 0、一点常用指令列表一、Ubuntu下复制与移动,cp/mv二、Ubuntu下echo 与 重定向>,>>三、Ubuntu下chmod,用户权限四、Ubuntu下的tar打包,gzip压缩五、Ubuntu(22.04)下系统语言为中文,切换主目录文件名为英文。六、Ubun…...
Visual Studio 进行单元测试【入门】
摘要:在软件开发中,单元测试是一种重要的实践,通过验证代码的正确性,帮助开发者提高代码质量。本文将介绍如何在VisualStudio中进行单元测试,包括创建测试项目、编写测试代码、运行测试以及查看结果。 1. 什么是单元测…...
【经验分享】Linux 系统安装后内核参数优化
在 Linux 系统安装后,进行内核优化有助于提升系统的性能、稳定性和安全性。以下是一些常见的内核优化操作: 修改/etc/sysctl.conf 文件 执行sysctl -p使配置生效。 kernel.shmmax 135185569792 kernel.shmall 4294967296 fs.aio-max-nr 3145728 fs.fi…...
linux统计文件夹下有多少个.rst文件行数小于4行
您可以使用 find 命令结合 wc 命令来统计文件夹下 .rst 文件行数小于 4 行的文件数量。以下是一个具体的命令示例: find /path/to/directory -name "*.rst" -type f -exec wc -l {} | awk $1 < 4 | wc -l解释: find /path/to/directory …...
使用开源项目xxl-cache构建多级缓存
xxl-cache简介 官网地址:https://www.xuxueli.com/xxl-cache/ 概述 XXL-CACHE 是一个 多级缓存框架,高效组合本地缓存和分布式缓存(RedisCaffeine),支持“多级缓存、一致性保障、TTL、Category隔离、防穿透”等能力;拥有“高性…...
LVDS接口总结--(5)IDELAY3仿真
仿真参考资料如下: https://zhuanlan.zhihu.com/p/386057087 timescale 1 ns/1 ps module tb_idelay3_ctrl();parameter REF_CLK 2.5 ; // 400MHzparameter DIN_CLK 3.3 ; // 300MHzreg ref_clk ;reg …...
Vue3(1)
一.create-vue // new Vue() 创建一个应用实例 > createApp() // createRouter() createStore() // 将创建实例进行了封装,保证每个实例的独立封闭性import { createApp } from vue import App from ./App.vue// mount 设置挂载点 #app (id为app的盒子) createA…...
玩转适配器模式
文章目录 解决方案现实的举例适用场景实现方式适配器模式优缺点优点:缺点:适配器模式可比上一篇的工厂模式好理解多了,工厂模式要具有抽象的思维。这个适配器模式,正如字面意思,就是要去适配某一件物品。 假如你正在开发一款股票市场监测程序, 它会从不同来源下载 XML 格…...
2.11寒假作业
web:[SWPUCTF 2022 新生赛]js_sign 打开环境是这样的,随便输入进行看看 提示错误,看源码其中的js代码 这个代码很容易理解,要让输入的内容等于对应的字符串,显然直接复制粘贴是错的 这串字符看起来像是base64加密&…...
untiy 冰面与地面,物理材质的影响
效果 WeChat_20250211165601...
视频编解码标准中的 Profile 和 Level
视频编解码标准中的 Profile 和 Level 在视频编码标准(如 H.264/AVC、HEVC/H.265、H.266/VVC、AV1)中,Profile(配置文件) 和 Level(级别) 是两个重要的概念,它们用于定义编码器和解码器支持的特性、功能以及视频质量与编码效率之间的权衡。 Profile(配置文件) Pro…...
通用的将jar制作成docker镜像sh脚本
通用的将jar制作成docker镜像sh脚本 为了在将 JAR 制作成 Docker 镜像的过程中创建日志目录,可以对之前的脚本进行扩展。以下是改进后的脚本,会在镜像构建时在容器内创建日志目录,并将日志文件挂载到该目录下。 在生成的 Dockerfile 中添加…...
AUTOGPT:基于GPT模型开发的实验性开源应用程序; 目标设定与分解 ;;自主思考与决策 ;;信息交互与执行
目录 AUTOGPT是一款基于GPT模型开发的实验性开源应用程序目标设定与分解自主思考与决策信息交互与执行AUTOGPT是一款基于GPT模型开发的实验性开源应用程序 目标设定与分解 自主思考与决策 信息交互与执行 AUTOGPT是一款基于GPT模型开发的实验性开源应用程序,它能让大语言模…...
Docker 运行 Kafka 带 SASL 认证教程
Docker 运行 Kafka 带 SASL 认证教程 Docker 运行 Kafka 带 SASL 认证教程一、说明二、环境准备三、编写 Docker Compose 和 jaas文件docker-compose.yml代码说明:server_jaas.conf 四、启动服务五、验证服务六、连接kafka服务七、总结 Docker 运行 Kafka 带 SASL 认…...
抖音增长新引擎:品融电商,一站式全案代运营领跑者
抖音增长新引擎:品融电商,一站式全案代运营领跑者 在抖音这个日活超7亿的流量汪洋中,品牌如何破浪前行?自建团队成本高、效果难控;碎片化运营又难成合力——这正是许多企业面临的增长困局。品融电商以「抖音全案代运营…...
【android bluetooth 框架分析 04】【bt-framework 层详解 1】【BluetoothProperties介绍】
1. BluetoothProperties介绍 libsysprop/srcs/android/sysprop/BluetoothProperties.sysprop BluetoothProperties.sysprop 是 Android AOSP 中的一种 系统属性定义文件(System Property Definition File),用于声明和管理 Bluetooth 模块相…...
论文解读:交大港大上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架(一)
宇树机器人多姿态起立控制强化学习框架论文解析 论文解读:交大&港大&上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架(一) 论文解读:交大&港大&上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化…...
使用 SymPy 进行向量和矩阵的高级操作
在科学计算和工程领域,向量和矩阵操作是解决问题的核心技能之一。Python 的 SymPy 库提供了强大的符号计算功能,能够高效地处理向量和矩阵的各种操作。本文将深入探讨如何使用 SymPy 进行向量和矩阵的创建、合并以及维度拓展等操作,并通过具体…...
Xen Server服务器释放磁盘空间
disk.sh #!/bin/bashcd /run/sr-mount/e54f0646-ae11-0457-b64f-eba4673b824c # 全部虚拟机物理磁盘文件存储 a$(ls -l | awk {print $NF} | cut -d. -f1) # 使用中的虚拟机物理磁盘文件 b$(xe vm-disk-list --multiple | grep uuid | awk {print $NF})printf "%s\n"…...
动态 Web 开发技术入门篇
一、HTTP 协议核心 1.1 HTTP 基础 协议全称 :HyperText Transfer Protocol(超文本传输协议) 默认端口 :HTTP 使用 80 端口,HTTPS 使用 443 端口。 请求方法 : GET :用于获取资源,…...
基于鸿蒙(HarmonyOS5)的打车小程序
1. 开发环境准备 安装DevEco Studio (鸿蒙官方IDE)配置HarmonyOS SDK申请开发者账号和必要的API密钥 2. 项目结构设计 ├── entry │ ├── src │ │ ├── main │ │ │ ├── ets │ │ │ │ ├── pages │ │ │ │ │ ├── H…...
Neko虚拟浏览器远程协作方案:Docker+内网穿透技术部署实践
前言:本文将向开发者介绍一款创新性协作工具——Neko虚拟浏览器。在数字化协作场景中,跨地域的团队常需面对实时共享屏幕、协同编辑文档等需求。通过本指南,你将掌握在Ubuntu系统中使用容器化技术部署该工具的具体方案,并结合内网…...
uni-app学习笔记三十五--扩展组件的安装和使用
由于内置组件不能满足日常开发需要,uniapp官方也提供了众多的扩展组件供我们使用。由于不是内置组件,需要安装才能使用。 一、安装扩展插件 安装方法: 1.访问uniapp官方文档组件部分:组件使用的入门教程 | uni-app官网 点击左侧…...
