面试官:“谈谈Spring中都用到了那些设计模式?”。

Spring 框架用到了哪些设计模式? 在博客中,我会通过丰富的示例代码和实际案例,详细介绍Spring框架中各种设计模式的应用场景和原理。通过这些设计模式,Spring框架实现了松耦合、可扩展和可维护的架构,使得开发者可以更加专注于业务逻辑的实现,而无需过多关注底层的细节。通过这些设计模式,Spring框架实现了松耦合、可扩展和可维护的架构,使得开发者可以更加专注于业务逻辑的实现,而无需过多关注底层的细节。当我们深入探索Spring框架时,可以发现其中涵盖了许多常见的设计模式,这些模式为我们构建稳健、灵活的应用程序提供了强大的支持。 阅读详情

本文公众号来源:JavaGuide 作者:JavaGuide


我在面试的时候,凡是问到Spring,我也总喜欢往设计模式上扯(显得自己学过设计模式,hahahha),这篇文章写得很不错,给大家分享一下。


(我之前也写过Spring和设计模式的文章,在公众号的菜单栏可以找到)

JDK 中用到了那些设计模式?Spring 中用到了那些设计模式?这两个问题,在面试中比较常见。我在网上搜索了一下关于 Spring 中设计模式的讲解几乎都是千篇一律,而且大部分都年代久远。所以,花了几天时间自己总结了一下,由于我的个人能力有限,文中如有任何错误各位都可以指出。另外,文章篇幅有限,对于设计模式以及一些源码的解读我只是一笔带过,这篇文章的主要目的是回顾一下 Spring 中的常见的设计模式。

Design Patterns(设计模式) 表示面向对象软件开发中最好的计算机编程实践。 Spring 框架中广泛使用了不同类型的设计模式,下面我们来看看到底有哪些设计模式?

控制反转(IoC)和依赖注入(DI)

IoC(Inversion of Control,控制翻转) 是Spring 中一个非常非常重要的概念,它不是什么技术,而是一种解耦的设计思想。它的主要目的是借助于“第三方”(Spring 中的 IOC 容器) 实现具有依赖关系的对象之间的解耦(IOC容易管理对象,你只管使用即可),从而降低代码之间的耦合度。IOC 是一个原则,而不是一个模式,以下模式(但不限于)实现了IoC原则。

640?wx_fmt=png
ioc-patterns

Spring IOC 容器就像是一个工厂一样,当我们需要创建一个对象的时候,只需要配置好配置文件/注解即可,完全不用考虑对象是如何被创建出来的。 IOC 容器负责创建对象,将对象连接在一起,配置这些对象,并从创建中处理这些对象的整个生命周期,直到它们被完全销毁。

在实际项目中一个 Service 类如果有几百甚至上千个类作为它的底层,我们需要实例化这个 Service,你可能要每次都要搞清这个 Service 所有底层类的构造函数,这可能会把人逼疯。如果利用 IOC 的话,你只需要配置好,然后在需要的地方引用就行了,这大大增加了项目的可维护性且降低了开发难度。关于Spring IOC 的理解,推荐看这一下知乎的一个回答:https://www.zhihu.com/question/23277575/answer/169698662 ,非常不错。

控制翻转怎么理解呢? 举个例子:"对象a 依赖了对象 b,当对象 a 需要使用 对象 b的时候必须自己去创建。但是当系统引入了 IOC 容器后, 对象a 和对象 b 之前就失去了直接的联系。这个时候,当对象 a 需要使用 对象 b的时候, 我们可以指定 IOC 容器去创建一个对象b注入到对象 a 中"。 对象 a 获得依赖对象 b 的过程,由主动行为变为了被动行为,控制权翻转,这就是控制反转名字的由来。

DI(Dependecy Inject,依赖注入)是实现控制反转的一种设计模式,依赖注入就是将实例变量传入到一个对象中去。

工厂设计模式

Spring使用工厂模式可以通过 BeanFactory 或 ApplicationContext 创建 bean 对象。

两者对比:

  • BeanFactory :延迟注入(使用到某个 bean 的时候才会注入),相比于ApplicationContext来说会占用更少的内存,程序启动速度更快。

  • ApplicationContext :容器启动的时候,不管你用没用到,一次性创建所有 bean 。BeanFactory 仅提供了最基本的依赖注入支持,ApplicationContext 扩展了 BeanFactory ,除了有BeanFactory的功能还有额外更多功能,所以一般开发人员使用ApplicationContext会更多。

ApplicationContext的三个实现类:

  1. ClassPathXmlApplication:把上下文文件当成类路径资源。

  2. FileSystemXmlApplication:从文件系统中的 XML 文件载入上下文定义信息。

  3. XmlWebApplicationContext:从Web系统中的XML文件载入上下文定义信息。

Example:

import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;public class App {    public static void main(String[] args) {        ApplicationContext context = new FileSystemXmlApplicationContext(                "C:/work/IOC Containers/springframework.applicationcontext/src/main/resources/bean-factory-config.xml");        HelloApplicationContext obj = (HelloApplicationContext) context.getBean("helloApplicationContext");        obj.getMsg();    }}

单例设计模式

在我们的系统中,有一些对象其实我们只需要一个,比如说:线程池、缓存、对话框、注册表、日志对象、充当打印机、显卡等设备驱动程序的对象。事实上,这一类对象只能有一个实例,如果制造出多个实例就可能会导致一些问题的产生,比如:程序的行为异常、资源使用过量、或者不一致性的结果。

使用单例模式的好处:

  • 对于频繁使用的对象,可以省略创建对象所花费的时间,这对于那些重量级对象而言,是非常可观的一笔系统开销;

  • 由于 new 操作的次数减少,因而对系统内存的使用频率也会降低,这将减轻 GC 压力,缩短 GC 停顿时间。

Spring 中 bean 的默认作用域就是 singleton(单例)的。 除了 singleton 作用域,Spring 中 bean 还有下面几种作用域:

  • prototype : 每次请求都会创建一个新的 bean 实例。

  • request : 每一次HTTP请求都会产生一个新的bean,该bean仅在当前HTTP request内有效。

  • session : 每一次HTTP请求都会产生一个新的 bean,该bean仅在当前 HTTP session 内有效。

  • global-session: 全局session作用域,仅仅在基于portlet的web应用中才有意义,Spring5已经没有了。Portlet是能够生成语义代码(例如:HTML)片段的小型Java Web插件。它们基于portlet容器,可以像servlet一样处理HTTP请求。但是,与 servlet 不同,每个 portlet 都有不同的会话

Spring 实现单例的方式:

  • xml:<bean id="userService" class="top.snailclimb.UserService" scope="singleton"/>

  • 注解:@Scope(value = "singleton")

Spring 通过 ConcurrentHashMap 实现单例注册表的特殊方式实现单例模式。Spring 实现单例的核心代码如下:

// 通过 ConcurrentHashMap(线程安全) 实现单例注册表private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {        Assert.notNull(beanName, "'beanName' must not be null");        synchronized (this.singletonObjects) {            // 检查缓存中是否存在实例              Object singletonObject = this.singletonObjects.get(beanName);            if (singletonObject == null) {                //...省略了很多代码                try {                    singletonObject = singletonFactory.getObject();                }                //...省略了很多代码                // 如果实例对象在不存在,我们注册到单例注册表中。                addSingleton(beanName, singletonObject);            }            return (singletonObject != NULL_OBJECT ? singletonObject : null);        }    }    //将对象添加到单例注册表    protected void addSingleton(String beanName, Object singletonObject) {            synchronized (this.singletonObjects) {                this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));            }        }}

代理设计模式

代理模式在 AOP 中的应用

AOP(Aspect-Oriented Programming:面向切面编程)能够将那些与业务无关,却为业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来,便于减少系统的重复代码,降低模块间的耦合度,并有利于未来的可拓展性和可维护性。

Spring AOP 就是基于动态代理的,如果要代理的对象,实现了某个接口,那么Spring AOP会使用JDK Proxy,去创建代理对象,而对于没有实现接口的对象,就无法使用 JDK Proxy 去进行代理了,这时候Spring AOP会使用Cglib ,这时候Spring AOP会使用 Cglib 生成一个被代理对象的子类来作为代理,如下图所示:

640?wx_fmt=jpeg
SpringAOPProcess

当然你也可以使用 AspectJ ,Spring AOP 已经集成了AspectJ ,AspectJ 应该算的上是 Java 生态系统中最完整的 AOP 框架了。

使用 AOP 之后我们可以把一些通用功能抽象出来,在需要用到的地方直接使用即可,这样大大简化了代码量。我们需要增加新功能时也方便,这样也提高了系统扩展性。日志功能、事务管理等等场景都用到了 AOP 。

Spring AOP 和 AspectJ AOP 有什么区别?

Spring AOP 属于运行时增强,而 AspectJ 是编译时增强。 Spring AOP 基于代理(Proxying),而 AspectJ 基于字节码操作(Bytecode Manipulation)。

Spring AOP 已经集成了 AspectJ ,AspectJ 应该算的上是 Java 生态系统中最完整的 AOP 框架了。AspectJ 相比于 Spring AOP 功能更加强大,但是 Spring AOP 相对来说更简单,

如果我们的切面比较少,那么两者性能差异不大。但是,当切面太多的话,最好选择 AspectJ ,它比Spring AOP 快很多。

模板方法

模板方法模式是一种行为设计模式,它定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。 模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤的实现方式。

640?wx_fmt=jpeg
模板方法UML图
public abstract class Template {    //这是我们的模板方法    public final void TemplateMethod(){        PrimitiveOperation1();          PrimitiveOperation2();        PrimitiveOperation3();    }    protected void  PrimitiveOperation1(){        //当前类实现    }    //被子类实现的方法    protected abstract void PrimitiveOperation2();    protected abstract void PrimitiveOperation3();}public class TemplateImpl extends Template {    @Override    public void PrimitiveOperation2() {        //当前类实现    }    @Override    public void PrimitiveOperation3() {        //当前类实现    }}

Spring 中 jdbcTemplate、hibernateTemplate 等以 Template 结尾的对数据库操作的类,它们就使用到了模板模式。一般情况下,我们都是使用继承的方式来实现模板模式,但是 Spring 并没有使用这种方式,而是使用Callback 模式与模板方法模式配合,既达到了代码复用的效果,同时增加了灵活性。

观察者模式

观察者模式是一种对象行为型模式。它表示的是一种对象与对象之间具有依赖关系,当一个对象发生改变的时候,这个对象所依赖的对象也会做出反应。Spring 事件驱动模型就是观察者模式很经典的一个应用。Spring 事件驱动模型非常有用,在很多场景都可以解耦我们的代码。比如我们每次添加商品的时候都需要重新更新商品索引,这个时候就可以利用观察者模式来解决这个问题。

Spring 事件驱动模型中的三种角色

事件角色

ApplicationEvent (org.springframework.context包下)充当事件的角色,这是一个抽象类,它继承了java.util.EventObject并实现了 java.io.Serializable接口。

Spring 中默认存在以下事件,他们都是对 ApplicationContextEvent 的实现(继承自ApplicationContextEvent):

  • ContextStartedEvent:ApplicationContext 启动后触发的事件;

  • ContextStoppedEvent:ApplicationContext 停止后触发的事件;

  • ContextRefreshedEvent:ApplicationContext 初始化或刷新完成后触发的事件;

  • ContextClosedEvent:ApplicationContext 关闭后触发的事件。

640?wx_fmt=png
ApplicationEvent-Subclass
事件监听者角色

ApplicationListener 充当了事件监听者角色,它是一个接口,里面只定义了一个 onApplicationEvent()方法来处理ApplicationEvent。ApplicationListener接口类源码如下,可以看出接口定义看出接口中的事件只要实现了 ApplicationEvent就可以了。所以,在 Spring中我们只要实现 ApplicationListener 接口实现 onApplicationEvent() 方法即可完成监听事件

package org.springframework.context;import java.util.EventListener;@FunctionalInterfacepublic interface ApplicationListener<E extends ApplicationEvent> extends EventListener {    void onApplicationEvent(E var1);}
事件发布者角色

ApplicationEventPublisher 充当了事件的发布者,它也是一个接口。

@FunctionalInterfacepublic interface ApplicationEventPublisher {    default void publishEvent(ApplicationEvent event) {        this.publishEvent((Object)event);    }    void publishEvent(Object var1);}

ApplicationEventPublisher 接口的publishEvent()这个方法在AbstractApplicationContext类中被实现,阅读这个方法的实现,你会发现实际上事件真正是通过ApplicationEventMulticaster来广播出去的。具体内容过多,就不在这里分析了,后面可能会单独写一篇文章提到。

Spring 的事件流程总结

  1. 定义一个事件: 实现一个继承自 ApplicationEvent,并且写相应的构造函数;

  2. 定义一个事件监听者:实现 ApplicationListener 接口,重写 onApplicationEvent() 方法;

  3. 使用事件发布者发布消息: 可以通过 ApplicationEventPublisher 的 publishEvent() 方法发布消息。

Example:

// 定义一个事件,继承自ApplicationEvent并且写相应的构造函数public class DemoEvent extends ApplicationEvent{    private static final long serialVersionUID = 1L;    private String message;    public DemoEvent(Object source,String message){        super(source);        this.message = message;    }    public String getMessage() {         return message;          }// 定义一个事件监听者,实现ApplicationListener接口,重写 onApplicationEvent() 方法;@Componentpublic class DemoListener implements ApplicationListener<DemoEvent>{    //使用onApplicationEvent接收消息    @Override    public void onApplicationEvent(DemoEvent event) {        String msg = event.getMessage();        System.out.println("接收到的信息是:"+msg);    }}// 发布事件,可以通过ApplicationEventPublisher  的 publishEvent() 方法发布消息。@Componentpublic class DemoPublisher {    @Autowired    ApplicationContext applicationContext;    public void publish(String message){        //发布事件        applicationContext.publishEvent(new DemoEvent(this, message));    }}

当调用 DemoPublisher 的 publish() 方法的时候,比如 demoPublisher.publish("你好") ,控制台就会打印出:接收到的信息是:你好 。

适配器模式

适配器模式(Adapter Pattern) 将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。

spring AOP中的适配器模式

我们知道 Spring AOP 的实现是基于代理模式,但是 Spring AOP 的增强或通知(Advice)使用到了适配器模式,与之相关的接口是AdvisorAdapter 。Advice 常用的类型有:BeforeAdvice(目标方法调用前,前置通知)、AfterAdvice(目标方法调用后,后置通知)、AfterReturningAdvice(目标方法执行结束后,return之前)等等。每个类型Advice(通知)都有对应的拦截器:MethodBeforeAdviceInterceptor、AfterReturningAdviceAdapter、AfterReturningAdviceInterceptor。Spring预定义的通知要通过对应的适配器,适配成 MethodInterceptor接口(方法拦截器)类型的对象(如:MethodBeforeAdviceInterceptor 负责适配 MethodBeforeAdvice)。

spring MVC中的适配器模式

在Spring MVC中,DispatcherServlet 根据请求信息调用 HandlerMapping,解析请求对应的 Handler。解析到对应的 Handler(也就是我们平常说的 Controller 控制器)后,开始由HandlerAdapter 适配器处理。HandlerAdapter 作为期望接口,具体的适配器实现类用于对目标类进行适配,Controller 作为需要适配的类。

为什么要在 Spring MVC 中使用适配器模式? Spring MVC 中的 Controller 种类众多,不同类型的 Controller 通过不同的方法来对请求进行处理。如果不利用适配器模式的话,DispatcherServlet 直接获取对应类型的 Controller,需要的自行来判断,像下面这段代码一样:

if(mappedHandler.getHandler() instanceof MultiActionController){     ((MultiActionController)mappedHandler.getHandler()).xxx  }else if(mappedHandler.getHandler() instanceof XXX){      ...  }else if(...){     ...  }  

假如我们再增加一个 Controller类型就要在上面代码中再加入一行 判断语句,这种形式就使得程序难以维护,也违反了设计模式中的开闭原则 – 对扩展开放,对修改关闭。

装饰者模式

装饰者模式可以动态地给对象添加一些额外的属性或行为。相比于使用继承,装饰者模式更加灵活。简单点儿说就是当我们需要修改原有的功能,但我们又不愿直接去修改原有的代码时,设计一个Decorator套在原有代码外面。其实在 JDK 中就有很多地方用到了装饰者模式,比如 InputStream家族,InputStream 类下有 FileInputStream (读取文件)、BufferedInputStream (增加缓存,使读取文件速度大大提升)等子类都在不修改InputStream 代码的情况下扩展了它的功能。

640?wx_fmt=png
装饰者模式示意图

Spring 中配置 DataSource 的时候,DataSource 可能是不同的数据库和数据源。我们能否根据客户的需求在少修改原有类的代码下动态切换不同的数据源?这个时候就要用到装饰者模式(这一点我自己还没太理解具体原理)。Spring 中用到的包装器模式在类名上含有 Wrapper或者 Decorator。这些类基本上都是动态地给一个对象添加一些额外的职责

总结

Spring 框架中用到了哪些设计模式:

  • 工厂设计模式 : Spring使用工厂模式通过 BeanFactory、ApplicationContext 创建 bean 对象。

  • 代理设计模式 : Spring AOP 功能的实现。

  • 单例设计模式 : Spring 中的 Bean 默认都是单例的。

  • 模板方法模式 : Spring 中 jdbcTemplate、hibernateTemplate 等以 Template 结尾的对数据库操作的类,它们就使用到了模板模式。

  • 包装器设计模式 : 我们的项目需要连接多个数据库,而且不同的客户在每次访问中根据需要会去访问不同的数据库。这种模式让我们可以根据客户的需求能够动态切换不同的数据源。

  • 观察者模式: Spring 事件驱动模型就是观察者模式很经典的一个应用。

  • 适配器模式 :Spring AOP 的增强或通知(Advice)使用到了适配器模式、spring MVC 中也是用到了适配器模式适配Controller。

  • ……

推荐阅读

640?wx_fmt=jpeg

欢迎关注640?wx_fmt=png点个再看640?wx_fmt=png

JMeter脚本录制-快速上手篇 有的项目应用场景下,压测时,需要考虑带宽因素,压测不只是压测接口,静态资源也要一起压测。一般来说,静态资源比较多,如果一个个手工去写请求,是比较繁琐的,此时,可以使用Jmeter的脚本录制功能。 步骤1,创建脚本录制模版。 JMeter菜单:文件>模版,下拉选择到Recording,点击“Create”按钮; 填写录制参数: hostToRecord:填写要录制的主机域名,例如,我们这里填入:www.baidu.com schemeToRecord:填写要录制的模式,例如,htt... 阅读详情

相关推荐

CP2102 USB 转 UART 模块 PCB 设计项目

不幸的是,我的笔记本电脑只有 USB 端口,所以我需要在 USB 端口和 UART 接口之间进行转换。PCB 布局将足够小,因此我们不一定需要高速布线 USB 线路,但我们将在此将其作为一个简单的示例来实现,以展示如何在这种类型的电路板上实现它。相反,我们只使用屏幕左侧的电路。在这里,我们利用对之间的间距和到 L1 上的铜灌注的距离将差分阻抗设置为目标值。初始布局分为两个部分:USB 连接器和 USB 线路的 TVS 二极管放置在电路板左侧,带有二极管 D4 和 D5 的引脚接头放置在电路板右侧。

jkh920184196的博客 2402

设计模式——访问者模式(Visitor Pattern)+ Spring相关源码

访问者模式,将 数据结构 与 数据操作 分离。

码鹿的记录 1500

BSL编程语言 —— 系统化程序设计

BSL编程语言简介 文章目录0. 选择编程语言1. 写简单的表达式(Expression) 0. 选择编程语言 如果你第一次使用DrRacket,打开后需要选择Beginning Student Language (BSL) Language -> Choose Language (或直接按Ctrl + L),看到如下洁面后选择Beginning Student,点击OK 定义区【De...

CSDoneRight的博客 6451

Spring中所使用的设计模式

Spring是一个非常优秀的开源框架,项目源码中所使用的设计模式随处可见,这篇文章主要记录一下Spring中常见的设计模式: (1)工厂模式:Spring使用工厂模式,通过BeanFactory和ApplicationContext来创建对象 (2)单例模式:Bean默认为单例模式 (3)策略模式:例如Resource的实现类,针对不同的资源文件,实现了不同方式的资源获取策略 (4)代理模式:Spring的AOP功能用到了JDK的动态代理和CGLIB字节码生成技术 (5)模板方法:可以将相同部分

张维鹏的博客 4万+

SUMO使用教程(一)

本人的sumo视频入门课程,希望支持哦。https://edu.youkuaiyun.com/course/detail/25834 SUMO是一款交通仿真软件,其余可自行百度。教程一主要展示一下如何运行一个仿真实例。当然,这只是实现方法中的一种。 准备: 1.SUMO软件 2.osm地图文件 SUMO可去官网下载,解压后就可以使用,图形界面软是在解压后bin文件夹下的sumo-gui.exe。...

lyx的专栏 3万+

HFSS螺旋线圈的设计与仿真

undefined.全局变量在这里进行设置:Project/Project Properties, browse and setup the global variables.undefined.方程中的局部变量设置:HFSS/Design Properties, browse and setup the local variables。按照下图填写曲线的方程内容:fill the parameters according to the setup in the following picture。

johnboat的专栏 3847

使用Hystrix的插件机制,Java中高级核心知识全面解析(1)

public class App { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext( “C:/work/IOC Containers/springframework.applicationcontext/src/main/resources/bean-factory- config.xml”); HelloApplicationContext

m0_60707060的博客 308

别再用Selenium被秒封了!2026最新反爬全突破+动态渲染实战(通过率99%)

做爬虫的同学,肯定都有过这样的经历:遇到一个纯前端渲染的网站,Requests抓包只能拿到一堆空的div标签,所有数据都是JS动态生成的。这时候你想到了Selenium,结果刚打开浏览器,网站直接跳出来一个"检测到机器人访问"的页面,或者直接返回403。我之前做一个跨境电商的爬虫项目,就踩了这个大坑。一开始用默认的Selenium ChromeDriver,10次请求有9次被封,通过率不到10%。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1387

面试官:“谈谈Spring中都用到了那些设计模式?”

  JDK 中用到了那些设计模式?Spring 中用到了那些设计模式?这两个问题,在面试中比较常见。我在网上搜索了一下关于 Spring 中设计模式的讲解几乎都是千篇一律,而且大部分都年代久远。所以,花了几天时间自己总结了一下,由于我的个人能力有限,文中如有任何错误各位都可以指出。另外,文章篇幅有限,对于设计模式以及一些源码的解读我只是一笔带过,这篇文章的主要目的是回顾一下 Spring 中的设计...

weixin_34368949的博客 284

手把手教你学Simulink——基于全桥 LLC 谐振变换器的双向 DC-DC 建模与仿真

本文详细介绍了基于Simulink的双向全桥LLC谐振变换器建模与仿真方法。内容涵盖:1)LLC谐振变换器背景与双向化挑战;2)系统架构设计及关键数学推导(FHA增益分析、双向控制逻辑);3)Simulink建模步骤(功率级搭建、PWM生成、同步整流实现);4)仿真结果分析(正向/反向工作验证、ZVS特性);5)工程实践建议(增益微调、代码生成与HIL测试)。通过手把手教学,帮助读者掌握950V↔48V双向LLC变换器的完整设计流程,实现高效率能量双向流动的同时保持软开关特性,适用于储能系统、车载充电等应用

MHD0815的博客 179

QT实现计算器(C/C++)

digitClicked()槽函数用于处理数字按钮的点击事件,operatorClicked()槽函数用于处理运算符按钮的点击事件,equalsClicked()槽函数用于处理等号按钮的点击事件。在operatorClicked()槽函数中,我们获取被点击按钮的文本作为当前运算符,并将文本框中的内容转换为双精度浮点数,存储为操作数1。在上述代码中,我们添加了一个私有成员变量m_operand1,用于存储第一个操作数的值,以及一个私有成员变量m_currentOperator,用于存储当前运算符的值。

CyberNova的博客 385

面试官:“谈谈Spring中都用到了那些设计模式?”

JDK 中用到了那些设计模式?Spring 中用到了那些设计模式?这两个问题,在面试中比较常见。我在网上搜索了一下关于 Spring 中设计模式的讲解几乎都是千篇一律,而且大部分都年代久远。所以,花了几天时间自己总结了一下,由于我的个人能力有限,文中如有任何错误各位都可以指出。另外,文章篇幅有限,对于设计模式以及一些源码的解读我只是一笔带过,这篇文章的主要目的是回顾一下 Spring 中的常见的设计模式。Design Patterns(设计模式) 表示面向对象软件开发中最好的计算机编程实践。 Spring

Moonxiyue的博客 310

别让 Claude Code 一直问你“能不能执行“:权限配置完全指南

Claude Code 提供了一套精细的权限配置机制,配置好权限设置,可以提速不少。这个小技巧需要掌握一下。

沐风 3844

【Spring 设计模式】面试官:“谈谈Spring中都用到了那些设计模式?”

目录 控制反转(IoC)和依赖注入(DI) 工厂设计模式 单例设计模式 代理设计模式 代理模式在 AOP 中的应用 Spring AOP 和 AspectJ AOP 有什么区别? 模板方法 观察者模式 Spring 事件驱动模型中的三种角色 Spring 的事件流程总结 适配器模式 spring AOP中的适配器模式 spring MVC中的适配器模式 装饰者模式 总...

凡是过往,皆为序章 435

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

spring中的设计模式_面试官:“谈谈Spring中都用到了那些设计模式?”。

JDK 中用到了那些设计模式?Spring 中用到了那些设计模式?这两个问题,在面试中比较常见。我在网上搜索了一下关于 Spring 中设计模式的讲解几乎都是千篇一律,而且大部分都年代久远。所以,花了几天时间自己总结了一下,由于我的个人能力有限,文中如有任何错误各位都可以指出。另外,文章篇幅有限,对于设计模式以及一些源码的解读我只是一笔带过,这篇文章的主要目的是回顾一下 Spring 中的设计模...

weixin_39595320的博客 1579

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 【吐血推荐】什么是领域驱动设计?DDD?
下一篇: 《大型网站系统与Java中间件》读书笔记 (二)
Java3y
Java3y 领域专家: 后端开发技术领域 领域专家: 后端开发技术领域
博客等级 码龄9年 1万+粉丝 509原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值