Java设计模式全集-适配器模式(Adapter)

适配器模式(Adapter)

运用于在现有几套不同的组件,互相间的接口定义不一致,又期望让他们可以协同工作,可以通过实现一套适配器,让本身无法兼容的组件可以协同工作了
mybatis中兼容了很多日志组件,不同的日志组件中又定义了不同的日志级别,因此mybatis定义了一套标准的日志级别,然后针对不同的日志组件,开发一套不同的适配器,让兼容的日志组件得以对应到mybatis的日志级别上
举个例子,你买了一个欧版水货数码产品,充电器的插头和国内的国标接口不一样,所以我们需要买一个转换头(适配器),让本来不能在国标插座上充电的设备能正常充电了

接口适配器

  • 接口一
/**
 * @author Xiaoyingge
 * @description
 * @date 2020/4/27 0:51
 */
public interface InterfaceA {

    String saySomething (String xxx);

}
  • 接口一实现
/**
 * @author Xiaoyingge
 * @description
 * @date 2020/4/27 0:57
 */
public class AImpl implements InterfaceA {

    @Override
    public String saySomething (String xxx) {
        return "1234" + xxx;
    }
}
  • 接口二
/**
 * @author Xiaoyingge
 * @description
 * @date 2020/4/27 0:55
 */
public interface InterfaceB {

    Long printLong (Long number);

}

  • 适配器
/**
 * @author Xiaoyingge
 * @description
 * @date 2020/4/27 0:56
 */
public class Adapter extends AImpl implements InterfaceB {

    @Override
    public Long printLong (Long number) {
        //适配过程
        return number + Long.parseLong(saySomething("555"));
    }
}
  • 测试
/**
 * @author Xiaoyingge
 * @description
 * @date 2020/4/27 0:59
 */
public class Main {

    public static void main (String[] args) {
        Adapter adapter = new Adapter();
        Long aLong = adapter.printLong(1L);
        System.out.println(aLong);
    }
}

类适配器

  • 接口定义

/**
 * @author Xiaoyingge
 * @description
 * @date 2020/4/27 0:51
 */
public interface InterfaceA {

    String saySomething (String xxx);

}

  • 接口实现
/**
 * @author Xiaoyingge
 * @description
 * @date 2020/4/27 1:02
 */
public class AImpl implements InterfaceA {

    private Person person;

    public AImpl (Person person) {
        this.person = person;
    }

    @Override
    public String saySomething (String xxx) {
        return this.person.print();
    }
}
  • 需要适配对象
/**
 * @author Xiaoyingge
 * @description
 * @date 2020/4/27 1:02
 */
public class Person {

    public String print () {
        System.out.println("od");
        return "sxxx";
    }
}

  • 将对象传入进行适配

/**
 * @author Xiaoyingge
 * @description
 * @date 2020/4/27 1:04
 */
public class Main {

    public static void main (String[] args) {
        AImpl a = new AImpl(new Person());
        a.saySomething("ss");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值