设计模式 第八节 适配器模式(Adapter)

1、 将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。
2、 特点:注重兼容、转换。适配者与被适配这之间没有层级关系,也没有必然联系。
3、 应用场景:编码解码、一拖三充电头、HDMI 转VGA、Type-C 转USB
    Spring AOP 模块对BeforeAdvice、AfterAdvice、ThrowsAdvice 三种通知类型的支持实际上是借助适配器模式来实现的
4、 优点:
        可以让两个没有关联的类一起运行,起着中间转换的作用;
        灵活性好,不会破坏原有的系统。
        可以让两个不相干的类一起运行,无需修改旧代码,灵活性好。
    缺点:过多地使用适配器,容易使代码结构混乱,如明明看到调用的是 A 接口,内部调用的却是 B 接口的实现。
5、 适配器主要分为两种:类适配器。对象适配器。
6、 类适配器和对象适配器最大的区别就在于:类适配器中的 Adapter 多继承于 Target 和 Adaptee 。由于 Java 不支持多继承,所以比较常用对象适配器。
    而在对象适配器中,Adapter 和 Adaptee 是依赖关系,也可以说是组合关系。同时 Target 是接口( 其实也可以是类 )。
7、 适配器适合用于解决新旧系统( 或新旧接口 )之间的兼容问题,而不建议在一开始就直接使用。

public interface IDoctor {
    public void gotoDoctor(String hospital);
}

public class FindDoctor {

    public void gotoBeijingThree(){
        System.out.println("去北京大学第三医院");
    }

    public void gotoChaoyang(){
        System.out.println("去朝阳医院");
    }

    public void gotoXiehe(){
        System.out.println("去协和医院");
    }
}


public class DoctorAdapter implements IDoctor{
    private FindDoctor findDoctor;

    public DoctorAdapter(){
        findDoctor = new FindDoctor();
    }

    @Override
    public void gotoDoctor(String hospital){
        if("three".equals(hospital)){
            findDoctor.gotoBeijingThree();
        }else if("cy".equals(hospital)){
            findDoctor.gotoChaoyang();
        }else if("xh".equals(hospital)){
            findDoctor.gotoXiehe();
        }

    }
}

public class AdapterTest {
    public static void main(String[] args) {
        DoctorAdapter doctorAdapter = new DoctorAdapter();
        doctorAdapter.gotoDoctor("cy");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值