定义:

    Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.(将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。) -设计模式之禅 第2版

    我的理解是,适配器模式的作用是兼容,将不兼容的类或对象通过适配器来转为目标类所兼容的类

    因此,适配器模式由三个角色组成

    • 目标类:Target
    • 适配器类:Adapter
    • 不兼容类:Adaptee

    举个例子来使用下,比如说要兼容一个第三方的信息.我的信息是String ,而这个第三方的信息是byte[]

    类图如下:

    1. public interface IMsg {
    2. public String getMsg();
    3. }
    1. @AllArgsConstructor
    2. public class Msg implements IMsg{
    3. private String msg;
    4. @Override
    5. public String getMsg() {
    6. return msg;
    7. }
    8. }
    1. public interface IOuterMsg {
    2. byte[] getMsg();
    3. }
    1. @AllArgsConstructor
    2. public class OuterMsg implements IOuterMsg {
    3. private byte[] msg;
    4. @Override
    5. public byte[] getMsg() {
    6. return msg;
    7. }
    8. }
    1. @AllArgsConstructor
    2. public class MsgAdapter implements IMsg {
    3. private OuterMsg msg;
    4. private int getLen(byte[] msg){
    5. int len = 0;
    6. for (byte b : msg) {
    7. if (b=='\0'){
    8. break;
    9. }
    10. len++;
    11. }
    12. return len;
    13. }
    14. @Override
    15. public String getMsg() {
    16. byte[] bytes = msg.getMsg();
    17. return new String(bytes,0,getLen(bytes));
    18. }
    19. }
    1. public class Client {
    2. public static void main(String[] args) {
    3. byte[] bytes = new byte[255];
    4. try(InputStream in = new FileInputStream("/home/zjm/桌面/test")){
    5. in.read(bytes);
    6. } catch (FileNotFoundException e) {
    7. e.printStackTrace();
    8. } catch (IOException e) {
    9. e.printStackTrace();
    10. }
    11. IMsg msg = new MsgAdapter(new OuterMsg(bytes));
    12. System.out.println(msg.getMsg());
    13. }
    14. }