简介:
适配器模式属于结构性设计模式。功能是将一个类的接口转换成其他使用者希望的另外一个接口,这样使得原来由于接口兼容问题不能使用的接口也可以使用了。常见于新老系统兼容问题处理。
具体实现及代码测试如下
/**
* 被适配的类
* @author dedu
*
*/
public class Adaptee {
public void message() {
System.out.println("我是原有系统接口对象");
}
}
/**
* 适配器(可使用类适配方式或者对象适配方式进行实现)
* @author dedu
*
*/
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void handle() {
System.out.println("进行适配");
adaptee.message();
}
}
class AdapterExt extends Adaptee implements Target {
@Override
public void handle() {
System.out.println("进行适配");
super.message();
}
}
public interface Target {
/**
* 希望的接口方式
*/
void handle();
}
/**
* 客户端接口
* @author dedu
*
*/
public class Client {
public void receive(Target target) {
target.handle();
}
}
测试
//JDK中,InputStreamReader OutputStreamWriter就是基于适配器模式
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
Client client = new Client();
client.receive(target);
}