定义:
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[]
类图如下:
public interface IMsg {public String getMsg();}
@AllArgsConstructorpublic class Msg implements IMsg{private String msg;@Overridepublic String getMsg() {return msg;}}
public interface IOuterMsg {byte[] getMsg();}
@AllArgsConstructorpublic class OuterMsg implements IOuterMsg {private byte[] msg;@Overridepublic byte[] getMsg() {return msg;}}
@AllArgsConstructorpublic class MsgAdapter implements IMsg {private OuterMsg msg;private int getLen(byte[] msg){int len = 0;for (byte b : msg) {if (b=='\0'){break;}len++;}return len;}@Overridepublic String getMsg() {byte[] bytes = msg.getMsg();return new String(bytes,0,getLen(bytes));}}
public class Client {public static void main(String[] args) {byte[] bytes = new byte[255];try(InputStream in = new FileInputStream("/home/zjm/桌面/test")){in.read(bytes);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}IMsg msg = new MsgAdapter(new OuterMsg(bytes));System.out.println(msg.getMsg());}}
