将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能在一起工作的那些类可以一起工作。
适配器模式属于结构模式。
Adapter类,通过继承src类,实现dst类接口,完成src->dst的适配。
以生活中充电器的例子来讲解适配器,充电器本省相当于Adapter,220V交流电相当于src(即被适配者),我们的dst(即目标)是5V直流电。
类图:
public class Voltage220V{
public int output220V(){
int src = 220;
System.out.println("电压=" + src + "伏");
return src;
}
}
public interface IVotage5V {
int output5V();
}
public class VoltageAdapter extends Voltage220V implement IVoltage5V {
@Override
public int output5V(){
int srv = output220V();
return src/4;
}
}
public class Phone {
//充电
public void chargin(IVotage5V ivotage5V){
if(ivotage5V.output5V() == 5){
System.out.printlin("电压为5V,可以充电");
}else if(iVotage5V.output5V() > 5){
System.out.println("电压大于5V,不能充电");
}
}
}
public class Client{
public static void main(String[] args){
System.out.println("===类适配器模式===");
Phone phone = new Phone();
phone.charging(new VoltageAdapter());
}
}
public class Voltage220V{
public int output220V(){
int src = 220;
System.out.println("电压=" + src + "伏");
return src;
}
}
public interface IVotage5V {
int output5V();
}
public class VoltageAdapter implement IVoltage5V {
private final Voltage220V voltage220V;
public VoltageAdapter(Voltage220V voltage220V){
this.voltage220V = voltage220V;
}
@Override
public int output5V(){
int srv = voltage220V.output220V();
return src/4;
}
}
public class Phone {
//充电
public void chargin(IVotage5V ivotage5V){
if(ivotage5V.output5V() == 5){
System.out.printlin("电压为5V,可以充电");
}else if(iVotage5V.output5V() > 5){
System.out.println("电压大于5V,不能充电");
}
}
}
public class Client{
public static void main(String[] args){
System.out.println("===类适配器模式===");
Phone phone = new Phone();
phone.charging(new VoltageAdapter());
}
}
注
以上示例引用自尚硅谷设计模式教程
https://www.bilibili.com/video/BV1G4411c7N4?p=62&spm_id_from=pageDriver&vd_source=3141b9fdb12c5901aa70919c50575543