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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值