设计模式-适配器模式

1.定义

适配器模式把一个类的接口换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起。

2.分类

有两种适配器:类的适配器模式,对象的适配器模式

类的适配器模式

public interface DC5 {
    public int outputDC5V();
}

public class AC220 {
    public int output220(){
        int v=220;
        return v;
    }
}

public class MyAdapter extends AC220 implements DC5{
    public int outputDC5V() {
        return output220()/44;
    }

public class Test {
    public static void main(String[] args) {
        MyAdapter myAdapter = new MyAdapter();
        System.out.println("适配器输出的结果:"+myAdapter.outputDC5V());
    }
}

优缺点:

       优点:由于Adapter继承了Adaptee类,所以它可以根据需求重写Adapter类的方法,使得Adapter的灵活行增强了。

       缺点:因为Java单继承的缘故,Target类必须是接口,以便与Adapter并实现了Target,完成适配的功能,但这样就导致了Adapter里暴漏了Adapter类的方法,使用起来的成本就增加了。

对象的适配器模式

public interface DC5 {
    public int outputDC5V();
}

public class AC220 {
    public int output220(){
        int v=220;
        return v;
    }
}

public class MyAdapter implements DC5 {
    public MyAdapter(AC220 ac220) {
        this.ac220 = ac220;
    }

    private AC220 ac220;

    public int outputDC5V() {
        return ac220.output220();
    }
}

public class Test {
    public static void main(String[] args) {
        MyAdapter myAdapter = new MyAdapter(new AC220());
        System.out.println("适配器输出的电流:"+myAdapter.outputDC5V());
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值