适配器模式是一种结构型设计模式, 它能使接口不兼容的对象能够相互合作。
参考:适配器模式
以下参考了狂神B站视频
1. 继承方式(类适配器)/**
* @description: 网线,模拟要被适配的类
* @author: anyue.long
* @date: 2022/4/23 10:15
*/
public class NetworkCable {
public void request() {
System.out.println("我是网线,用来连接上网的");
}
}
/**
* @description: 转接头,模拟适配器的抽象实现,定义成接口
* @author: anyue.long
* @date: 2022/4/23 10:22
*/
public interface IAdapter {
// 处理请求
void handlerRequest();
}
/**
* @description: 模拟具体的适配器,需要继承被适配类,实现适配器接口
* @author: anyue.long
* @date: 2022/4/23 10:26
*/
public class NetworkAdapter extends NetworkCable implements IAdapter{
@Override
public void handlerRequest() {
super.request();
}
}
/**
* @description: 电脑,模拟目标类,需要用到被适配类
* @author: anyue.long
* @date: 2022/4/23 10:19
*/
public class Computer {
// 上网,通过转接头连接上网线,即通过适配器来使用被适配类的方法
public void netPlay(IAdapter networkAdapter) {
networkAdapter.handlerRequest();
}
}
/**
* @description: 模拟客户端
* @author: anyue.long
* @date: 2022/4/23 10:36
*/
public class Client {
public static void main(String[] args) {
Computer computer = new Computer();
NetworkAdapter networkAdapter = new NetworkAdapter();
computer.netPlay(networkAdapter);
}
}
2. 组合方式(对象适配器)
/**
* @description: 模拟具体的适配器,需要继承被适配类,实现适配器接口
* @author: anyue.long
* @date: 2022/4/23 10:26
*/
public class NetworkAdapter implements IAdapter {
private final NetworkCable networkCable;
public NetworkAdapter(NetworkCable networkCable) {
this.networkCable = networkCable;
}
@Override
public void handlerRequest() {
networkCable.request();
}
}
/**
* @description: 模拟客户端
* @author: anyue.long
* @date: 2022/4/23 10:36
*/
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);
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)