适配器模式
适配器模式(相当于转接头),需要两个已有的接口。
将一个类的接口转为客服希望的接口,将由于接口不兼容而不能一起工作的两个类可以协同一起工作。转接匹配,功能复用。
适用场景:
1 系统需要使用现有的类,而这些类的接口不符合系统的需要。
2 想要建立一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作。
3 需要一个统一的输出接口,而输入端的类型不可预知。
public interface ServiceA {
void request();
}
public interface ServiceB {
void net();
}
public class ServiceAImpl implements ServiceA {
@Override
public void request() {
System.out.println("电脑");
}
}
public class ServiceBImple implements ServiceB{
@Override
public void net() {
System.out.println("连接上了网络");
}
}
public class Adapter{
private ServiceB serviceB;
public Adapter(ServiceB serviceB) {
this.serviceB = serviceB;
}
public void request(ServiceA serviceA) {
serviceA.request();
serviceB.net();
}
}
public class AdapterPattern {
public static void main(String[] args) {
Adapter adapter = new Adapter(new ServiceBImple());
adapter.request(new ServiceAImpl());
}
}
常见的使用场景有IO的InputstreamReader,这个类将 inputstream输入流接口和Reader接口用适配器模式连接起来一起工作。具体代码如下:
这里继承Reader,传入InputStream流,将这两个接口融合到StreamDecoder,
这个StreamDecoder就相当于是适配类。而InputStreamReader是StreamDecoder包装出去的使用类。
public class InputStreamReader extends Reader {
//这个类是Reader实现类
private final StreamDecoder sd;
public InputStreamReader(InputStream in) {
super(in);
try {
this.sd = StreamDecoder.forInputStreamReader(in, this, (String)null);
} catch (UnsupportedEncodingException var3) {
throw new Error(var3);
}
}
}
InputStreamReader 的读取操作底层都是使用StreamDecoder去读的,而
StreamDecoder 是通过InputStream去读的,通过Reader提供的输出字符流。
简简单单就把适配器讲完了,但是适配器模式运用是很灵活的。用好适配器能解决很多问题,努力吧,道友们。