簡(jiǎn)介
將一個(gè)類的接口轉(zhuǎn)換成客戶希望的另一個(gè)接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些類可以在一起工作软瞎。
適配器模式有三種:類適配器逢唤、對(duì)象適配器拉讯、接口適配器
前二者在實(shí)現(xiàn)上有些許區(qū)別,作用一樣鳖藕,第三個(gè)接口適配器差別較大魔慷。
場(chǎng)景
- 用來做舊系統(tǒng)改造和升級(jí)
- 如果一個(gè)接口中定義的抽象方法過多,而子類中很多抽象方法又不需要用到著恩,就應(yīng)該設(shè)計(jì)一個(gè)適配器盖彭。
模式中的角色
- 目標(biāo)接口(Target)
客戶所期待的接口。目標(biāo)接口時(shí)具體的或抽象的類页滚,也可以是接口。 - 需要是適配的類(Adaptee)
需要適配的類或適配者類铺呵。 - 適配器(Adapter)
通過包裝一個(gè)需要適配的對(duì)象裹驰,把原接口轉(zhuǎn)換成目標(biāo)接口。
類適配器片挂、對(duì)象適配器
UML
image.png
- 客戶端:
package com.amberweather.adapter;
/**
*
* 客戶端類幻林,筆記本電腦
* 插鍵盤需要usb接口
* @author HT
*
*/
public class Client {
//客戶端需要傳入usb接口
public void test1(Target t){
t.handleRequest();
}
public static void main(String[] args) {
Client c = new Client();
Adaptee a = new Adaptee();
Target t = new Adapter();
c.test1(t);
}
}
- 客戶端當(dāng)前需要的接口:
package com.amberweather.adapter;
/**
* 表示客戶端用到的當(dāng)前的接口
* usb接口
* @author HT
*
*/
public interface Target {
void handleRequest();
}
- 需要調(diào)用,但接口不支持的類:
package com.amberweather.adapter;
/**
*
* 被適配的對(duì)象
* 例如鍵盤
* @author HT
*
*/
public class Adaptee {
public void request(){
System.out.println("我是一個(gè)鍵盤音念,但我是圓心插孔");
}
}
- 適配器(通過繼承實(shí)現(xiàn)):
package com.amberweather.adapter;
/**
* 類適配器方式
* 適配器
* 接口之間的轉(zhuǎn)換
* @author Administrator
*
*/
public class Adapter extends Adaptee implements Target {
@Override
public void handleRequest() {
super.request();
}
}
- 適配器(通過組合實(shí)現(xiàn)):
package com.amberweather.adapter;
/**
* 使用組合的方式實(shí)現(xiàn)適配器
*
* @author Administrator
*
*/
public class Adapter2 implements Target {
Adaptee a ;
@Override
public void handleRequest() {
a.request();
}
public Adapter2(Adaptee a) {
super();
this.a = a;
}
}
image.png
接口適配器
public interface A {
void a();
void b();
void c();
void d();
void e();
void f();
}
public abstract class Adapter implements A {
public void a(){}
public void b(){}
public void c(){}
public void d(){}
public void e(){}
public void f(){}
}
public class Ashili extends Adapter {
public void a(){
System.out.println("實(shí)現(xiàn)A方法被調(diào)用");
}
public void d(){
System.out.println("實(shí)現(xiàn)d方法被調(diào)用");
}
}
public class Client {
public static void main(String[] args) {
A a = new Ashili();
a.a();
a.d();
}
}