1.意圖
將一個類的接口轉換成客戶希望的接口,adapter模式使得原來由於接口不兼容的
而不能一起工作的那些類可以一起工作。
2.參與者
Target,Client,Adaptee,Adapter
3.相關模式
Bridge與對象適配器類似,但是出發點不同:Bridge目的是將接口部分和實現
部分分離,從而對它們可以較容易相對對立的加以改變。而adapter意味着改變
一個已有的接口
Decorator增強了其它對象的功能而同時不改變它的接口。因此decorator對應用
程序的透明性比adapter好,結果是decorator支持遞歸組合而純粹使用適配器
是不可能實現這一點的。
代理模式proxy在不改變接口的條件下爲另一個對象定義一個代理。
4.類適配器結構
5.類適配器代碼
public interface Target {
void playA();
}
public class ConcreteTarget implements Target {
@Override
public void playA() {
System.out.println("playA");
}
}
public class Adaptee {
void playB(){
System.out.println("playB");
}
}
public class Adapter extends Adaptee implements Target {
@Override
public void playA() {
super.playB();
}
}
public class Client {
public static void main(String[] args) {
Target t = new Adapter();
t.playA();
}
}
6.對象適配器結構
7.對象適配器代碼
public interface Adaptee {
void playA();
}
public class Adaptee1 implements Adaptee {
@Override
public void playA() {
System.out.println("Adaptee1");
}
}
public class Adaptee2 implements Adaptee {
@Override
public void playA() {
System.out.println("Adaptee2");
}
}
public interface Target {
void playB();
}
public class Adapter implements Target {
private Adaptee adaptee;
Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}
@Override
public void playB() {
adaptee.playA();
}
}
public class Client {
public static void main(String[] args) {
Adaptee a = new Adaptee1();
Target t = new Adapter(a);
t.playB();
Adaptee b = new Adaptee2();
Target t2 = new Adapter(b);
t2.playB();
}
}