java设计模式学习笔记-5-适配器模式

适配器

类适配器

public class Voltage220V{
    public int output220V(){
        int src = 220;
        return src;
    }
}

public Interface IVoltage5V{
    public int output5V();
}
//适配器类
public class VoltageAdapter extends Voltage220V implements IVoltage5V{
    public int output5V(){
        int srcV = output220V();
        int dstV = srcV / 44;
        return dstV
    }
}

public class Phone{
    public void charing(IVoltage5V iVoltage5V){
        if(iVoltage5V.output5V==5){
            //充电
        }else if(iVoltage5V.output5V>5){
            //无法充电
        }
    }
}

对象适配器

public class Voltage220V{
    public int output220V(){
        int src = 220;
        return src;
    }
}

public Interface IVoltage5V{
    public int output5V();
}
//适配器类
public class VoltageAdapter implements IVoltage5V{
    private Voltage220 voltage220;//持有而不再继承
    
    public VoltageAdapter(Voltage220 voltage220){
        this.voltage220 = voltage220;
    }
    
    public int output5V(){
        int dstV = 0;
        if(null != voltage220){
             int srcV = voltage220.output220V();
             dstV = srcV / 44;//进行转化
        }
        return dstV
    }
}

public class Phone{
    public void charing(IVoltage5V iVoltage5V){
        if(iVoltage5V.output5V==5){
            //充电
        }else if(iVoltage5V.output5V>5){
            //无法充电
        }
    }
}

接口适配器

public interface Interface{
    public void m1();
    public void m2();
}

public astract class AbsAdapter implements Interface{
    public void m1(){}
    public void m2(){}
}

public class Client{
    public static main(String[] args){
        AbsAdapter absAdapter = new AbsAdapter(){
            public void m1(){
                //定义实现方法
            }
        }
        absAdapter.m1();
    }
}
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页