适配器模式的本质:
转换匹配,复用功能
/*
* 已经存在的接口,这个接口需要被适配
*/
package com.impl;
public class Adaptee {
/*
* 示意方法,原本已经存在,已经实现的方法
*/
public void specificRequest(){
System.out.println("要被复用的方法");
}
}
/*
* 定义客户端使用的接口,与特定领域相关
*/
package com;
public interface Target {
/*
* 示意方法,客户段请求处理的方法
*/
void request();
}
/*
* 持有需要被适配的接口对象
*/
package com;
import com.impl.Adaptee;
public class Adapter implements Target {
/*
* 持有需要被适配的对象
*/
private Adaptee daptee;
public Adapter(Adaptee daptee){
this.daptee = daptee;
}
@Override
public void request() {
//可能转调已经实现了的方法,进行适配,可能要几个方法组合使用
daptee.specificRequest();
}
}
import com.Adapter;
import com.Target;
import com.impl.Adaptee;
public class Client {
public static void main(String[] args) {
//创建需要被适配的对象
Adaptee adaptee = new Adaptee();
//创建客户端需要调用的接口对象
Target target = new Adapter(adaptee);
//请求处理
target.request();
}
}