适配器模式(适用场景,旧系统的改造,而且有部分代码不能修改,要做兼容处理)
原有的usb接口
public interface Usb { void input(); }
原有的调用方法
public class Client { public void input(Usb usb){ usb.input(); } }
现在希望调用的方法
public class Ps2 {
public void ps2Input(){
System.out.println("ps2输入");
}
}
中间创建的过渡类
public class SwUsb2Ps2 implements Usb{ private static Ps2 ps2 = new Ps2(); @Override public void input() { ps2.ps2Input(); } }
JAVA中的输入流输出流包装就是用了适配器模式
InputStream inputStream = new FileInputStream(""); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); FileOutputStream fileOutputStream = new FileOutputStream(""); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);