适配器模式
1. 适配器模式使得原本无法兼容的类可以在一起工作
2. 实现过程
- 定义目标接口
public interface NetToUsb {
void handleRequest();
}
- 编写需要适配的类
public class Computer {
public void surfInternet(NetToUsb adapter) {
adapter.handleRequest();
}
}
public class NetworkLine {
public void request() {
System.out.println("network is sending request");
}
}
- 编写适配器类
@AllArgsConstructor
public class Adapter implements NetToUsb {
private NetworkLine networkLine;
public void handleRequest() {
networkLine.request();
}
}
- 测试
public class Main {
public static void main(String[] args) {
NetworkLine networkLine = new NetworkLine();
NetToUsb adapter = new Adapter(networkLine);
Computer computer = new Computer();
computer.surfInternet(adapter);
}
}