适配者模式案例(代码)讲解

设计模式的代码:https://github.com/Aerozb/design_patterns

实际应用:看springmvc适配器模式---HandlerAdapter

对象适配器:通过聚合方式,而不是直接继承

案例:220V电压通过充电器转成5V给手机充电

public class Voltage220V {

    public int output(){
        System.out.println("220v");
        return 220;
    }

}
public interface IVolatege5V {
    public int output5V();
}
public class VoltageAdapter implements IVolatege5V {
    private Voltage220V voltage220V;

    public VoltageAdapter(Voltage220V voltage220V) {
        this.voltage220V = voltage220V;
    }

    @Override
    public int output5V() {
        int v = 0;
        if (null != voltage220V) {
            v = voltage220V.output();
            v = v / 44;
            System.out.println(v + "V");
        }
        return v;
    }
}
public class Phone {
    private IVolatege5V iVolatege5V;

    public Phone(IVolatege5V iVolatege5V) {
        this.iVolatege5V = iVolatege5V;
    }

    public void charge() {
        int v = iVolatege5V.output5V();
        if (v == 5) {
            System.out.println("充电成功" + v + "V");
        }else {
            System.out.println("充电失败");
        }
    }
}
public class Client {
    public static void main(String[] args) {
        VoltageAdapter voltageAdapter=new VoltageAdapter(new Voltage220V());
        Phone phone=new Phone(voltageAdapter);
        phone.charge();
    }
}

结果:

220v
5V
充电成功5V

小结:VoltageAdapter 继承IVolatege5V 接口,聚合Voltage220V 类,手机类聚合IVolatege5V接口,调用output5V()方法,就会调用实现类的方法(即适配器),适配器会进行转换,用户端手机充电只要调用charge()方法充电就行,new的时候要把适配器加进去(就是5V的实现类)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值