适配器模式(Adapter Pattern)
半塘 2024/3/27 Java进阶
适配器模式本质就是做一层转换。
# 1、适配器模式案例
以手机用wifi上网,电脑用网线上网,为电脑加个适配器,实现电脑也可wifi上网
public interface PhoneNetWorld {
void wifi();
}
public class Phone implements PhoneNetWorld{
@Override
public void wifi() {
System.out.println("手机上网");
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
public interface ComputerNetWorld {
void networkCable();
}
public class Computer implements ComputerNetWorld{
@Override
public void networkCable() {
System.out.println("电脑上网");
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
本来电脑上网要通过Computer.networkCable()方式,现在Computer也想通过wifi()上网
public class ComputerWifiAdapter implements PhoneNetWorld{
private Computer computer;
public ComputerWifiAdapter(Computer computer) {
this.computer = computer;
}
@Override
public void wifi() {
computer.networkCable();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
public class ClientTest {
public static void main(String[] args) {
PhoneNetWorld phoneNetWorld = new Phone();
phoneNetWorld.wifi();
PhoneNetWorld computerNetWorld = new ComputerWifiAdapter(new Computer());
computerNetWorld.wifi();
}
}
/**
* 输出结果:
* 手机上网
* 电脑上网
* /
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14