GoF23 适配器模式学习笔记
将一个类的接口转换成客户希望的另一个接口,适配器模式使得原本由于不兼容而不能一起工作的类可以一起工作
对象适配器优点:
1. 一个对象适配器可以把多个不同的适配者适配到同一个目标
2. 可以适配一个适配者的子类,由于适配器和适配者是关联关系,根据“里氏代换原则”,适配者的子类也可以通过该适配器进行适配
类适配器缺点:
1. 对于Java等不支持多重类继承的语言,一次最多只能适配一个适配者类,不能同时适配多个适配者
2. 在Java等语言中,类适配器模式中的目标抽象类只能为接口,不能为类,其使用有局限性
应用场景:
1. 系统需要使用一些现有的类,而这些类的接口不符合系统的需要,甚至没有这些类的源代码
2. 想创建一个可以重复使用的类,用于与一些彼此之间没有太大关联的类,包括一些可能在将来引进的类
网线——网线USB接口转换器——电脑
package adapter;
public class Adaptee {
public void SurfTheInternet() {
System.out.println("Surf the Internet.");
}
}
package adapter;
public interface NetToUSB {
void handleRequest();
}
package adapter;
public class Adapter extends Adaptee implements NetToUSB{
@Override
public void handleRequest() {
super.SurfTheInternet();
}
}
package adapter;
public class AnotherAdapter implements NetToUSB{
private Adaptee adaptee;
public AnotherAdapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void handleRequest() {
adaptee.SurfTheInternet();
}
}
package adapter;
public class Computer {
public void SurfTheInternet(NetToUSB adapter) {
adapter.handleRequest();
}
}
package adapter;
public class Test {
public static void main(String[] args) {
Computer computer = new Computer();
Adapter adapter = new Adapter();
computer.SurfTheInternet(adapter);
Adaptee adaptee = new Adaptee();
AnotherAdapter anotherAdapter = new AnotherAdapter(adaptee);
computer.SurfTheInternet(anotherAdapter);
}
}