The Adapter pattern is a structural design pattern that allows you to convert the interface of a class into another interface that the client expects. Adapter pattern lets classes work together that couldn't otherwise because of incompatible interfaces.
定义目标接口
java
public interface Target {
void request();
}
创建适配器类
java
public class Adaptee {
public void specificRequest() {
System.out.println("Called specificRequest()");
}
}
实现适配器类
java
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
使用适配器模式
java
public class AdapterPatternDemo {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request();
}
}