将一个类的接口转换为客户希望的另外一个接口。包括类适配器和对象适配器。
//类适配器
public class ClassAdapter {
interface Target{
public abstract void targetMethod();
}
class Adaptee{
public void adapteeMethod(){
System.out.println("adapteeMethod...");
}
}
class Adapter extends Adaptee implements Target{
public void targetMethod() {
super.adapteeMethod();
}
}
public static void main(String[] args){
ClassAdapter ca = new ClassAdapter();
Target t = ca.new Adapter();
t.targetMethod();
}
}
//对象适配器
public class ObjectAdapter {
interface Target{
public abstract void targetMethod();
}
class Adaptee{
public void adapteeMethod(){
System.out.println("adapteeMethod...");
}
}
class Adapter implements Target{
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}
public void targetMethod() {
adaptee.adapteeMethod();
}
}
public static void main(String[] args){
ObjectAdapter ca = new ObjectAdapter();
Adaptee adptee = ca.new Adaptee();
Target t = ca.new Adapter(adptee);
t.targetMethod();
}
}