人人妻人人澡人人爽人人精品av_精品乱码一区内射人妻无码_老司机午夜福利视频_精品成品国色天香摄像头_99精品福利国产在线导航_野花社区在线观看视频_大地资源在线影视播放_东北高大肥胖丰满熟女_金门瓶马车内剧烈运动

首頁>國內(nèi) > 正文

面試官:談談Spring中用到了哪些設計模式?

2023-07-11 10:23:21來源:今日頭條

設計模式(Design pattern)代表了最佳的實踐,通常被有經(jīng)驗的面向對象的軟件開發(fā)人員所采用。設計模式是軟件開發(fā)人員在軟件開發(fā)過程中面臨的一般問題的解決方案。 Spring 框架中廣泛使用了不同類型的設計模式。

工廠模式

Spring使用工廠模式可以通過 BeanFactory 或 ApplicationContext 創(chuàng)建 bean 對象。

兩者對比:


(相關資料圖)

BeanFactory :延遲注入(使用到某個 bean 的時候才會注入),相比于BeanFactory來說會占用更少的內(nèi)存,程序啟動速度更快。ApplicationContext :容器啟動的時候,不管你用沒用到,一次性創(chuàng)建所有 bean 。BeanFactory 僅提供了最基本的依賴注入支持,ApplicationContext 擴展了 BeanFactory ,除了有BeanFactory的功能之外還有額外更多功能,所以一般開發(fā)人員使用ApplicationContext會更多。

ApplicationContext的三個實現(xiàn)類:

ClassPathXmlApplication:從類的根路徑下加載配置文件(推薦使用這種)FileSystemXmlApplication:它是從磁盤路徑上加載配置文件,配置文件可以在磁盤的任意位置。XmlWebApplicationContext:從Web系統(tǒng)中的XML文件載入上下文定義信息。AnnotationConfigApplicationContext:當使用注解配置容器對象時,需要使用此類來創(chuàng)建 spring 容器。它用來讀取注解。

Example:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");UserService userService = (UserService) applicationContext.getBean("userService");userService.save();
單例模式

在我們的系統(tǒng)中,有一些對象其實我們只需要一個,比如說:線程池、緩存、對話框、注冊表、日志對象、充當打印機、顯卡等設備驅動程序的對象。事實上,這一類對象只能有一個實例,如果制造出多個實例就可能會導致一些問題的產(chǎn)生,比如:程序的行為異常、資源使用過量、或者不一致性的結果。

使用單例模式的好處:

對于頻繁使用的對象,可以省略創(chuàng)建對象所花費的時間,這對于那些重量級對象而言,是非??捎^的一筆系統(tǒng)開銷;由于new操作的次數(shù)減少,因而對系統(tǒng)內(nèi)存的使用頻率也會降低,這將減輕GC壓力,縮短GC停頓時間。

Spring中bean的默認作用域就是singleton(單例)的,除了singleton作用域,Spring中bean還有下面幾種作用域:

prototype : 每次請求都會創(chuàng)建一個新的 bean 實例。request : 每一次HTTP請求都會產(chǎn)生一個新的bean,該bean僅在當前HTTP request內(nèi)有效。session : 每一次HTTP請求都會產(chǎn)生一個新的 bean,該bean僅在當前 HTTP session 內(nèi)有效。global-session: 全局session作用域,僅僅在基于portlet的web應用中才有意義,Spring5已經(jīng)沒有了。Portlet是能夠生成語義代碼(例如:HTML)片段的小型Java Web插件。它們基于portlet容器,可以像servlet一樣處理HTTP請求。但是,與 servlet 不同,每個 portlet 都有不同的會話

Spring實現(xiàn)單例的方式:

xml:注解:@Scope(value = “singleton”)

Spring通過ConcurrentHashMap實現(xiàn)單例注冊表的特殊方式實現(xiàn)單例模式。Spring實現(xiàn)單例的核心代碼如下:

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {    // 通過 ConcurrentHashMap(線程安全) 實現(xiàn)單例注冊表    private final Map singletonObjects = new ConcurrentHashMap(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(Aspect-Oriented Programming:面向切面編程)能夠將那些與業(yè)務無關,卻為業(yè)務模塊所共同調(diào)用的邏輯或責任(例如事務處理、日志管理、權限控制等)封裝起來,便于減少系統(tǒng)的重復代碼,降低模塊間的耦合度,并有利于未來的可拓展性和可維護性。

Spring AOP就是基于動態(tài)代理的,如果要代理的對象實現(xiàn)了某個接口,那么Spring AOP會使用JDK Proxy,去創(chuàng)建代理對象,而對于沒有實現(xiàn)接口的對象,Spring AOP會使用Cglib,這時候Spring AOP會使用Cglib生成一個被代理對象的子類來作為代理,如下圖所示:

當然你也可以使用AspectJ,Spring AOP以及集成了AspectJ,AspectJ應該算得上是Java生態(tài)系統(tǒng)中最完整的AOP框架了。

使用AOP之后我們可以把一些通用的功能抽象出來,在需要用到的地方直接使用即可,這樣大大簡化了代碼量。我們需要增加新功能時也方便,這樣也提高了系統(tǒng)擴展性。日志功能、事務管理等等場景都用到了 AOP 。

Spring AOP 和 AspectJ AOP 有什么區(qū)別?

Spring AOP 屬于運行時增強,而 AspectJ 是編譯時增強。 Spring AOP 基于代理(Proxying),而 AspectJ 基于字節(jié)碼操作(Bytecode Manipulation)。

Spring AOP 已經(jīng)集成了 AspectJ ,AspectJ 應該算的上是 Java 生態(tài)系統(tǒng)中最完整的 AOP 框架了。AspectJ 相比于 Spring AOP 功能更加強大,但是 Spring AOP 相對來說更簡單。如果我們的切面比較少,那么兩者性能差異不大。但是,當切面太多的話,最好選擇 AspectJ ,它比Spring AOP 快很多。

模板模式

模板模式是一種行為設計模式,它定義一個操作中的算法的骨架,而將一些步驟延遲到子類中。 模板方法使得子類可以不改變一個算法的結構即可重定義該算法的某些特定步驟的實現(xiàn)方式。

實例代碼:

public abstract class Template {    //這是我們的模板方法    public final void TemplateMethod(){        PrimitiveOperation1();          PrimitiveOperation2();        PrimitiveOperation3();    }    protected void  PrimitiveOperation1(){        //當前類實現(xiàn)    }    //被子類實現(xiàn)的方法    protected abstract void PrimitiveOperation2();    protected abstract void PrimitiveOperation3();}public class TemplateImpl extends Template {    @Override    public void PrimitiveOperation2() {        //當前類實現(xiàn)    }    @Override    public void PrimitiveOperation3() {        //當前類實現(xiàn)    }}
JDBC案例

定義抽象查詢父類

public abstract class AbstractDao {    /**     * 查詢     * @param sql     * @param params     * @return     */    protected Object find(String sql, Object[] params) {        Connection conn = null;        PreparedStatement ps = null;        ResultSet rs = null;        Object obj = null;        try {            conn = JDBCUtils.getConnection();            ps = conn.prepareStatement(sql);            for (int i = 0; i < params.length; i++) {                ps.setObject(i + 1, params[i]);            }            rs = ps.executeQuery();            while (rs.next()) {                obj = rowMapper(rs);            }        } catch (Exception e) {            e.printStackTrace();        } finally {            JDBCUtils.free(rs, ps, conn);        }        return obj;    }        protected abstract Object rowMapper(ResultSet rs) throws SQLException;        //同時可以添加 insert ,update 等方法}

具體的dao實現(xiàn)

public class UserDao extends AbstractDao {    public User findUser(int userId) {        String sql = "select * from t_user where userId = ?";        Object[] params = new Object[] { userId };        Object user = super.find(sql, params);        System.out.println((User) user);        return (User) user;    }    @Override    protected Object rowMapper(ResultSet rs) throws SQLException {        User user = new User();        user.setId(rs.getInt("userId"));        user.setName(rs.getString("name"));        user.setAge(rs.getInt("age"));        user.setSex(rs.getString("sex"));        user.setAddress(rs.getString("address"));        return user;    }}

對應的JDBC工具類和用戶實體

public class JDBCUtils {    private static String url = "jdbc:mysql://localhost:3306/jdbcstudy";    private static String user = "root";    private static String password = "123";    private JDBCUtils() {    }    static {        try {            Class.forName("com.mysql.jdbc.Driver");        } catch (ClassNotFoundException e) {            throw new ExceptionInInitializerError(e);        }    }    public static Connection getConnection() throws SQLException {        return DriverManager.getConnection(url, user, password);    }        public static void free(ResultSet rs, PreparedStatement ps, Connection conn){        if(rs != null){            try {                rs.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        if(ps != null){            try {                ps.close();            } catch (SQLException e) {                e.printStackTrace();            }        }                if(conn != null){            try {                conn.close();            } catch (SQLException e) {                e.printStackTrace();            }        }    }}public class User {    private Integer userId;    private String name;    private Integer age;    private String sex;    private String address;            //set...get省略    }
模板模式的優(yōu)點和不足

優(yōu)點

具體細節(jié)步驟實現(xiàn)定義在子類中,子類定義詳細處理算法是不會改變算法整體結構。代碼復用的基本技術,在數(shù)據(jù)庫設計中尤為重要。存在一種反向的控制結構,通過一個父類調(diào)用其子類的操作,通過子類對父類進行擴展增加新的行為,符合“開閉原則”。

不足

每個不同的實現(xiàn)都需要定義一個子類,會導致類的個數(shù)增加,系統(tǒng)更加龐大。

Spring 中 jdbcTemplate、hibernateTemplate 等以 Template 結尾的對數(shù)據(jù)庫操作的類,它們就使用到了模板模式。一般情況下,我們都是使用繼承的方式來實現(xiàn)模板模式,但是 Spring 并沒有使用這種方式,而是使用Callback 模式與模板方法模式配合,既達到了代碼復用的效果,同時增加了靈活性。

觀察者模式

觀察者模式是一種對象行為型模式。它表示的是一種對象與對象之間具有依賴關系,當一個對象發(fā)生改變的時候,這個對象所依賴的對象也會做出反應。Spring 事件驅動模型就是觀察者模式很經(jīng)典的一個應用。Spring 事件驅動模型非常有用,在很多場景都可以解耦我們的代碼。比如我們每次添加商品的時候都需要重新更新商品索引,這個時候就可以利用觀察者模式來解決這個問題。

觀察者模式是一種對象行為型模式。它表示的是一種對象與對象之間具有依賴關系,當一個對象發(fā)生改變的時候,這個對象所依賴的對象也會做出反應。Spring 事件驅動模型就是觀察者模式很經(jīng)典的一個應用。Spring 事件驅動模型非常有用,在很多場景都可以解耦我們的代碼。比如我們每次添加商品的時候都需要重新更新商品索引,這個時候就可以利用觀察者模式來解決這個問題。

Spring 事件驅動模型中的三種角色

事件角色

ApplicationEvent (org.springframework.context包下)充當事件的角色,這是一個抽象類,它繼承了java.util.EventObject并實現(xiàn)了 java.io.Serializable接口。

Spring 中默認存在以下事件,他們都是對 ApplicationContextEvent 的實現(xiàn)(繼承自ApplicationContextEvent):

ContextStartedEvent:ApplicationContext 啟動后觸發(fā)的事件;ContextStoppedEvent:ApplicationContext 停止后觸發(fā)的事件;ContextRefreshedEvent:ApplicationContext 初始化或刷新完成后觸發(fā)的事件;ContextClosedEvent:ApplicationContext 關閉后觸發(fā)的事件。事件監(jiān)聽者角色

ApplicationListener 充當了事件監(jiān)聽者角色,它是一個接口,里面只定義了一個 onApplicationEvent()方法來處理ApplicationEvent。ApplicationListener接口類源碼如下,可以看出接口定義看出接口中的事件只要實現(xiàn)了 ApplicationEvent就可以了。所以,在 Spring中我們只要實現(xiàn) ApplicationListener 接口實現(xiàn) onApplicationEvent() 方法即可完成監(jiān)聽事件

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

ApplicationEventPublisher 充當了事件的發(fā)布者,它也是一個接口。

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

ApplicationEventPublisher 接口的publishEvent()這個方法在AbstractApplicationContext類中被實現(xiàn),閱讀這個方法的實現(xiàn),你會發(fā)現(xiàn)實際上事件真正是通過ApplicationEventMulticaster來廣播出去的。具體內(nèi)容較多后續(xù)單獨分析。

Spring 的事件流程總結

定義一個事件: 實現(xiàn)一個繼承自 ApplicationEvent,并且寫相應的構造函數(shù);

定義一個事件監(jiān)聽者:實現(xiàn) ApplicationListener 接口,重寫 onApplicationEvent() 方法;

使用事件發(fā)布者發(fā)布消息: 可以通過 ApplicationEventPublisher 的 publishEvent() 方法發(fā)布消息。

案例如下:

// 定義一個事件,繼承自ApplicationEvent并且寫相應的構造函數(shù)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;          }// 定義一個事件監(jiān)聽者,實現(xiàn)ApplicationListener接口,重寫 onApplicationEvent() 方法;@Componentpublic class DemoListener implements ApplicationListener{    //使用onApplicationEvent接收消息    @Override    public void onApplicationEvent(DemoEvent event) {        String msg = event.getMessage();        System.out.println("接收到的信息是:"+msg);    }}// 發(fā)布事件,可以通過ApplicationEventPublisher  的 publishEvent() 方法發(fā)布消息。@Componentpublic class DemoPublisher {    @Autowired    ApplicationContext applicationContext;    public void publish(String message){        //發(fā)布事件        applicationContext.publishEvent(new DemoEvent(this, message));    }}

當調(diào)用 DemoPublisher 的 publish() 方法的時候,比如 demoPublisher.publish(“hello world!”) ,控制臺就會打印出:接收到的信息是:hello world!。

適配器模式

適配器模式(Adapter Pattern) 將一個接口轉換成客戶希望的另一個接口,適配器模式使接口不兼容的那些類可以一起工作,其別名為包裝器(Wrapper)。

spring AOP中的適配器模式

我們知道 Spring AOP 的實現(xiàn)是基于代理模式,但是 Spring AOP 的增強或通知(Advice)使用到了適配器模式,與之相關的接口是AdvisorAdapter 。Advice 常用的類型有:BeforeAdvice(目標方法調(diào)用前,前置通知)、AfterAdvice(目標方法調(diào)用后,后置通知)、AfterReturningAdvice(目標方法執(zhí)行結束后,return之前)等等。每個類型Advice(通知)都有對應的攔截器:MethodBeforeAdviceInterceptor、AfterReturningAdviceAdapter、AfterReturningAdviceInterceptor。Spring預定義的通知要通過對應的適配器,適配成 MethodInterceptor接口(方法攔截器)類型的對象(如:MethodBeforeAdviceInterceptor 負責適配 MethodBeforeAdvice)。

spring MVC中的適配器模式

在Spring MVC中,DispatcherServlet 根據(jù)請求信息調(diào)用 HandlerMapping,解析請求對應的 Handler。解析到對應的 Handler(也就是我們平常說的 Controller 控制器)后,開始由HandlerAdapter 適配器處理。HandlerAdapter 作為期望接口,具體的適配器實現(xiàn)類用于對目標類進行適配,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類型就要在上面代碼中再加入一行 判斷語句,這種形式就使得程序難以維護,也違反了設計模式中的開閉原則 – 對擴展開放,對修改關閉。

適配器模式的優(yōu)缺點

優(yōu)點:

能提高類的透明性和復用性,現(xiàn)有的類會被復用但不需要改變。目標類和適配器類解耦,可以提高程序的擴展性。在很多業(yè)務場景中符合開閉原則。

缺點:

在適配器代碼編寫過程中需要進行全面考慮,可能會增加系統(tǒng)復雜度。增加代碼閱讀難度,過多使用適配器會使系統(tǒng)代碼變得凌亂。裝飾者模式

裝飾者模式可以動態(tài)地給對象添加一些額外的屬性或行為。相比于使用繼承,裝飾者模式更加靈活。簡單點兒說就是當我們需要修改原有的功能,但我們又不愿直接去修改原有的代碼時,設計一個Decorator套在原有代碼外面。其實在 JDK 中就有很多地方用到了裝飾者模式,比如 InputStream家族,InputStream 類下有 FileInputStream (讀取文件)、BufferedInputStream (增加緩存,使讀取文件速度大大提升)等子類都在不修改InputStream 代碼的情況下擴展了它的功能。

裝飾者模式示意圖

在裝飾模式中的角色有:

抽象構件(Component)角色:給出一個抽象接口,以規(guī)范準備接收附加責任的對象。具體構件(ConcreteComponent)角色:定義一個將要接收附加責任的類。裝飾(Decorator)角色:持有一個構件(Component)對象的實例,并定義一個與抽象構件接口一致的接口。具體裝飾(ConcreteDecorator)角色:負責給構件對象“貼上”附加的責任。

Spring 中配置 DataSource 的時候,DataSource 可能是不同的數(shù)據(jù)庫和數(shù)據(jù)源。我們能否根據(jù)客戶的需求在少修改原有類的代碼下動態(tài)切換不同的數(shù)據(jù)源?這個時候就要用到裝飾者模式。Spring 中用到的包裝器模式在類名上含有 Wrapper或者 Decorator。這些類基本上都是動態(tài)地給一個對象添加一些額外的職責。

裝飾者模式和適配器模式對比

裝飾者模式和適配器模式都是包裝模式(Wrapper Pattern),裝飾者模式是一種特殊的代理模式,二者對比如下:

總結

Spring 框架中用到了哪些設計模式:

工廠設計模式 : Spring使用工廠模式通過 BeanFactory、ApplicationContext 創(chuàng)建 bean 對象。代理設計模式 : Spring AOP 功能的實現(xiàn)。單例設計模式 : Spring 中的 Bean 默認都是單例的。模板方法模式 : Spring 中 jdbcTemplate、hibernateTemplate 等以 Template 結尾的對數(shù)據(jù)庫操作的類,它們就使用到了模板模式。觀察者模式: Spring 事件驅動模型就是觀察者模式很經(jīng)典的一個應用。適配器模式 :Spring AOP 的增強或通知(Advice)使用到了適配器模式、spring MVC 中也是用到了適配器模式適配Controller。裝飾者(包裝器)設計模式 : 我們的項目需要連接多個數(shù)據(jù)庫,而且不同的客戶在每次訪問中根據(jù)需要會去訪問不同的數(shù)據(jù)庫。這種模式讓我們可以根據(jù)客戶的需求能夠動態(tài)切換不同的數(shù)據(jù)源。

關鍵詞:

相關新聞

Copyright 2015-2020   三好網(wǎng)  版權所有 聯(lián)系郵箱:435 22 [email protected]  備案號: 京ICP備2022022245號-21