Spring中的設計模式 介面卡模式

2021-07-11 07:23:04 字數 1917 閱讀 2589

適配模式的定義如下:

將乙個類的介面變換成客戶端所期待的另一種介面,從而使原本因介面不匹配兒無法在一起工作的兩個類能夠在一起工作。 

看下介面卡模式的類圖:

spring中也有介面卡模式的典型應用。 

在spring的aop中,使用的advice(通知)來增強被**類的功能。spring實現這一aop功能的原理就使用**模式(1、jdk動態**。2、cglib位元組碼生成技術**。)對類進行方法級別的切面增強,即,生成被**類的**類, 並在**類的方法前,設定***,通過執行***重的內容增強了**方法的功能,實現的面向切面程式設計。

advice(通知)的型別有:beforeadvice、afterreturningadvice、threowsadvice的。

在每個型別advice(通知)都有對應的***,methodbeforeadviceinterceptor、afterreturningadviceinterceptor、throwsadviceinterceptor。

spring需要將每個advice(通知)都封裝成對應的***型別,返回給容器,所以需要使用介面卡模式對advice進行轉換。下面我們看看具體的**。

methodbeforeadvice類:adaptee

public inte***ce methodbeforeadvice extends beforeadvice
adapter類介面:

target

public inte***ce advisoradapter
methodbeforeadviceadapter類,adapter

class methodbeforeadviceadapter implements advisoradapter, serializable 

public methodinterceptor getinterceptor(advisor advisor)

}

defaultadvisoradapterregistry類,client

public class defaultadvisoradapterregistry implements advisoradapterregistry, serializable 

public advisor wrap(object adviceobject) throws unknownadvicetypeexception

if (!(adviceobject instanceof advice))

advice advice = (advice) adviceobject;

if (advice instanceof methodinterceptor)

for (advisoradapter adapter : this.adapters)

} throw new unknownadvicetypeexception(advice);

} public methodinterceptor getinterceptors(advisor advisor) throws unknownadvicetypeexception

for (advisoradapter adapter : this.adapters)

} if (interceptors.isempty())

return interceptors.toarray(new methodinterceptor[interceptors.size()]);

} public void registeradvisoradapter(advisoradapter adapter)

}

設計模式 介面卡模式 類介面卡 物件介面卡

乙個小例子,便於理解,上 這是我們造的。現在想用這個方法。public class adaptee 類介面卡。對我們想要的方法封裝一下,target就能像之前一樣,呼叫request方法即可。public class adapter1 extends adaptee implements targe...

設計模式 介面卡模式(類介面卡和物件介面卡)

如果去歐洲國家去旅遊的話,他們的插座如下圖最左邊,是歐洲標準。而我們使用的插頭如下圖最右邊的。因此我們的膝上型電腦,手機在當地不能直接充電。所以就需要乙個插座轉換器,轉換器第1面插入當地的插座,第2麵供我們充電,這樣使得我們的插頭在當地能使用。生活中這樣的例子很多,手機充電器 將220v轉換為5v的...

設計模式中的介面卡模式

將乙個類的介面轉換成客戶希望的另外乙個介面。adapter模式使得原本由於介面不相容而不能一起工作的那些類可以在一起工作。比如 現在有個手機要充電,手機是5v的介面,我要用電源是220v的powera介面去充電,即呼叫power的方法charge 然而charge 只提供220v電源,而我們還有個5...