是一种结构性设计模式,将一个类的接口转化为客户希望的另一个接口,充当两个不同接口之间的桥梁,使得原来接口不兼容的类可以一起工作
?//目标接口
?public interface Target {
??
? ? ?void request();
?}
?public class Adaptee {
? ? ?void get(){
? ? ? ? ?System.out.println("成功");
? ? }
?}
?public class Adapter implements Target{
??
? ? ?//持有一个被适配者
? ? ?private Adaptee adaptee;
??
? ? ?public Adapter(Adaptee adaptee) {
? ? ? ? ?this.adaptee = adaptee;
? ? }
??
? ? ?@Override
? ? ?public void request() {
? ? ? ? ?adaptee.get();
? ? }
?}
?public class Client {
? ? ?public static void main(String[] args) {
? ? ? ? ?Target target = new Adapter(new Adaptee());
? ? ? ? ?target.request();
? ? }
?}
作用:
将客户端代码和具体的类解耦,客户端不需要直到被适配者的细节
具有良好的拓展性
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
while (num-->0){
int t = scanner.nextInt();
if(t ==1){
computer computer = new computer();
computer.chargeWithTypeC();
}else{
AdapterCharger adapterCharger = new AdapterCharger();
adapterCharger.charge();
}
}
}
}
interface USB{
void charge();
}
interface TypeC{
void chargeWithTypeC();
}
class TypeAdapter implements USB{
private TypeC typeC;
public TypeAdapter(TypeC typeC){
this.typeC = typeC;
}
@Override
public void charge() {
typeC.chargeWithTypeC();
}
}
//新电脑使用Type
class computer implements TypeC{
@Override
public void chargeWithTypeC() {
System.out.println("TypeC");
}
}
class AdapterCharger implements USB{
@Override
public void charge() {
System.out.println("USB Adapter");
}
}