适配器模式分为类适配器和对象适配器,两个不同接口的实现类中,适配器类持有另外一个类的引用称之为对象适配器。适配器类继承另外一个类并实现自己的接口称之为类适配器。
对象适配器:
public class Ps2ObjectAdapter implements Ps2 {
private Usb usb;
public Ps2ObjectAdapter(){
usb = new UsbImpl();
}
@Override
public void isPs2() {
usb.isUsb();
}
public static void main(String[] args) {
Ps2 ps2 = new Ps2ObjectAdapter();
ps2.isPs2();
}
}
类适配器:
public class Ps2ClassAdapter extends UsbImpl implements Ps2 {
@Override
public void isPs2() {
isUsb();
}
public static void main(String[] args) {
Ps2 ps2 = new Ps2ClassAdapter();
ps2.isPs2();
}
}
I/O流中的InputStreamReader和OutputStreamWriter就是运用了对象适配器
/**
* Creates an InputStreamReader that uses the default charset.
*
* @param in An InputStream
*/
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## check lock object
} catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
从代码中可以看到,InputStreamReader的构造方法中传入了一个InputStream的引用,使用的是对象适配器模式。