Java 設(shè)計模式之適配器模式詳解
定義
適配器將一個類的接口,轉(zhuǎn)換成客戶期望另一個接口。適配器讓原本不兼容的類可以合作無間
結(jié)構(gòu)圖

如圖所示,兩腳插頭如何能插入三腳插座,可以在中間加一個適配器進(jìn)行轉(zhuǎn)換,就能實(shí)現(xiàn)兩腳插頭能插入三腳插座。
使用場景
- 新的代碼兼容舊的代碼
- 使用別人好的代碼到自己的代碼中
代碼實(shí)現(xiàn)
適配器模式有:對象適配器和類適配器
Java代碼實(shí)現(xiàn)
java沒有多繼承,只能實(shí)現(xiàn)對象適配器
先創(chuàng)建兩個接口
// 適配目標(biāo)接口
public interface Target{
public void aaa();
}
// 適配者接口
public interface Adaptee{
public void bbb();
}
實(shí)現(xiàn)這兩個接口
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)對象適配器和類適配器
這是對象適配器
# 適配目標(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è)計模式之適配器模式詳解的文章就介紹到這了,更多相關(guān)Java 設(shè)計模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springcloud hystrix服務(wù)熔斷和dashboard如何實(shí)現(xiàn)
這篇文章主要介紹了Springcloud hystrix服務(wù)熔斷和dashboard如何實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-12-12
JAVA實(shí)現(xiàn)空間索引編碼——GeoHash的示例
本篇文章主要介紹了JAVA實(shí)現(xiàn)空間索引編碼——GeoHash的示例,如何從眾多的位置信息中查找到離自己最近的位置,有興趣的朋友可以了解一下2016-10-10
SpringBoot項(xiàng)目整合Log4j2實(shí)現(xiàn)自定義日志打印失效問題解決
這篇文章主要介紹了SpringBoot項(xiàng)目整合Log4j2實(shí)現(xiàn)自定義日志打印失效問題解決,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-01-01

