Java 設(shè)計(jì)模式之適配器模式詳解
定義
適配器將一個(gè)類的接口,轉(zhuǎn)換成客戶期望另一個(gè)接口。適配器讓原本不兼容的類可以合作無間
結(jié)構(gòu)圖
如圖所示,兩腳插頭如何能插入三腳插座,可以在中間加一個(gè)適配器進(jìn)行轉(zhuǎn)換,就能實(shí)現(xiàn)兩腳插頭能插入三腳插座。
使用場(chǎng)景
- 新的代碼兼容舊的代碼
- 使用別人好的代碼到自己的代碼中
代碼實(shí)現(xiàn)
適配器模式有:對(duì)象適配器和類適配器
Java代碼實(shí)現(xiàn)
java沒有多繼承,只能實(shí)現(xiàn)對(duì)象適配器
先創(chuàng)建兩個(gè)接口
// 適配目標(biāo)接口 public interface Target{ public void aaa(); }
// 適配者接口 public interface Adaptee{ public void bbb(); }
實(shí)現(xiàn)這兩個(gè)接口
public class Targetimpl implements Target{ public void aaa(){ System.out.printnln("Target") } }
public class Adapteeimpl implements Adaptee{ public void bbb(){ System.out.printnln("Adaptee") } }
制作適配器
需要實(shí)現(xiàn)要適配成什么接口,需要實(shí)現(xiàn)什么接口
public class Adapter implements Target{ Adaptee adaptee; public Adapter(Adaptee adapter){ this.adaptee = adaptee; } public void aaa(){ adaptee.bbb() } }
public class Run{ public static void main(String[] args){ Adaptee adaptee = new Adatee(); Target target = new Targetimpl(); Target adapter = new Adapter(target); adaptee.aaa(); target.bbb(); adapter.aaa(); } }
運(yùn)行結(jié)果:
Target
Adaptee
Adaptee
Python代碼實(shí)現(xiàn)
Python可以實(shí)現(xiàn)對(duì)象適配器和類適配器
這是對(duì)象適配器
# 適配目標(biāo) class Target(object): def aaa(self): print("Target") # 被適配者 class Adaptee(object): def bbb(self): print("Adaptee") # 這是適配器 class Adapter(Target): def __init__(self, Adaptee): self.Adaptee = Adaptee def aaa(self): self.Adaptee.bbb() target = Target() adaptee = Adaptee() adapter = Adapter(adaptee) target.aaa() adaptee.bbb() adapter.aaa()
運(yùn)行結(jié)果:
Target
Adaptee
Adaptee
這是類適配器
class Target(object): def aaa(self): print("Target") class Adaptee(object): def bbb(self): print("Adaptee") class Adapter(Target, Adaptee): def aaa(self): self.bbb() target = Target() adaptee = Adaptee() adapter = Adapter() target.aaa() adaptee.bbb() adapter.aaa()
運(yùn)行結(jié)果:
Target
Adaptee
Adaptee
到此這篇關(guān)于Java 設(shè)計(jì)模式之適配器模式詳解的文章就介紹到這了,更多相關(guān)Java 設(shè)計(jì)模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springcloud hystrix服務(wù)熔斷和dashboard如何實(shí)現(xiàn)
這篇文章主要介紹了Springcloud hystrix服務(wù)熔斷和dashboard如何實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12JAVA實(shí)現(xiàn)空間索引編碼——GeoHash的示例
本篇文章主要介紹了JAVA實(shí)現(xiàn)空間索引編碼——GeoHash的示例,如何從眾多的位置信息中查找到離自己最近的位置,有興趣的朋友可以了解一下2016-10-10SpringBoot項(xiàng)目整合Log4j2實(shí)現(xiàn)自定義日志打印失效問題解決
這篇文章主要介紹了SpringBoot項(xiàng)目整合Log4j2實(shí)現(xiàn)自定義日志打印失效問題解決,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-01-01Java和SQL實(shí)現(xiàn)取兩個(gè)字符間的值
這篇文章主要介紹了Java和SQL實(shí)現(xiàn)取兩個(gè)字符間的值操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06java并發(fā)訪問重復(fù)請(qǐng)求過濾問題
本篇文章給大家分享了關(guān)于java并發(fā)訪問重復(fù)請(qǐng)求過濾的相關(guān)問題以及解決方法,對(duì)此有需要的朋友參考學(xué)習(xí)下。2018-05-05