java設計模式學習筆記-5-介面卡模式

weixin0605發表於2020-10-30

介面卡

類介面卡

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();
    }
}

相關文章