概述
将一个类的接口转化为客户希望的另外的一个接口,使得原本由于接口不兼容而不能一起工作的那些类一起工作。
结构
- 目标接口:当前业务所期待的接口
- 适配者类:需要适配的类或适配者类。
- 适配器类:通过继承或者引用适配者的对象,把适配者接口转化为目标接口。
//目标接口
interface SdCard{
String sdread();
void sdwrite(String msg);
}
interface TfCard{
String tfread();
void tfwrite(String msg);
}
//适配者
class TfCardImpl implements TfCard{
public String tfread(){
System.out.println("read tfcard");
}
public void tfwrite(String msg){
System.out.println("write tfcard:"+msg);
}
}
类适配器(采用继承的方式实现)
public SdAdapterTF extends TfCardImpl implements SdCard{
public String sdread(){
tfread();
}
public void sdwrite(String msg){
tfwrite(msg);
}
}
对象适配器(采用对象组合的方式实现)
public SdAdapterTF implements SdCard{
private TfCard tfcard;
public SdAdapterTf(TfCard tfcard){
this.tfcard=tfcard;
}
public String sdread(){
tfcard.tfread();
}
public void sdwrite(String msg){
tfcard.tfwrite(msg);
}
}
jdk中的源码
StreamDecoder对构造方法的字节流进行了封装,并通过该类实现了字节流和字符流之间的解码转化.
接口适配器
接口中定义了多个抽象方法,定义该适配器的子类时,子类只实现其中的部分抽象方法。
它适用于一个接口不想使用其所有的方法的情况。因此也称为单接口适配器模式。
servlet和GenericServlet
public interface Servlet {
void init(ServletConfig var1) throws ServletException;
ServletConfig getServletConfig();
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
String getServletInfo();
void destroy();
}
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
public GenericServlet() {
}
public void destroy() {
}
public ServletConfig getServletConfig() {
return this.config;
}
public String getServletInfo() {
return "";
}
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init() throws ServletException {
}
public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
}