适配器模式是一种结构型设计模式, 它能使接口不兼容的对象能够相互合作。
参考:适配器模式
以下参考了狂神B站视频
1. 继承方式(类适配器)
public class NetworkCable {
public void request() {
System.out.println("我是网线,用来连接上网的");
}
}
public interface IAdapter {
// 处理请求
void handlerRequest();
}
public class NetworkAdapter extends NetworkCable implements IAdapter{
@Override
public void handlerRequest() {
super.request();
}
}
public class Computer {
// 上网,通过转接头连接上网线,即通过适配器来使用被适配类的方法
public void netPlay(IAdapter networkAdapter) {
networkAdapter.handlerRequest();
}
}
public class Client {
public static void main(String[] args) {
Computer computer = new Computer();
NetworkAdapter networkAdapter = new NetworkAdapter();
computer.netPlay(networkAdapter);
}
}
2. 组合方式(对象适配器)
public class NetworkAdapter implements IAdapter {
private final NetworkCable networkCable;
public NetworkAdapter(NetworkCable networkCable) {
this.networkCable = networkCable;
}
@Override
public void handlerRequest() {
networkCable.request();
}
}
public class Client {
public static void main(String[] args) {
Computer computer = new Computer();
NetworkCable networkCable = new NetworkCable();
NetworkAdapter networkAdapter = new NetworkAdapter(networkCable);
computer.netPlay(networkAdapter);
}
}



