3个角色:源、适配器、目标
3种形式:
类适配器-一个源类(1个方法)、一个目标接口(2个方法)、一个适配器(继承源、实现接口);
对象适配器-一个源类(1个方法)、一个目标接口(2个方法)、一个适配器(组合源、实现接口);
接口适配器(缺省适配模式)-一个目标接口(多个方法)、一个抽象类(默认空实现所有接口方法)、用的时候new匿名抽象内部类覆盖单独的方法;
例子:springMvc的HandlerAdapter;
类适配器
UML类图:
代码实现:
/**
* 类适配器,通过继承方式扩展方法,适配接口
*/
//接口-目标
interface Target {
void method1();
void method2();
}
//源类
class Adaptee {
public void method1() {
System.out.println("method 1");
}
}
//适配器,继承源类,实现目标
class Adapter extends Adaptee implements Target {
@Override
public void method2() {
System.out.println("method 2");
}
}
public class ClassAdapter {
public static void main(String[] args) {
Target target = new Adapter();
target.method1();
target.method2();
}
}
对象适配器
UML类图:
代码实现:
/**
* 对象适配器,通过组合方式扩展方法,适配接口
*/
//接口-目标
interface Target {
void method1();
void method2();
}
//源类
class Adaptee {
public void method1() {
System.out.println("method 1");
}
}
//适配器,组合源类,实现目标
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void method1() {
adaptee.method1();
}
@Override
public void method2() {
System.out.println("method 2");
}
}
public class ObjectAdapter {
public static void main(String[] args) {
Target target = new Adapter(new Adaptee());
target.method1();
target.method2();
}
}
接口适配器(缺省适配模式)
UML类图:
代码实现:
/**
* 接口适配器,抽象实现方法、用的时候new匿名抽象内部类覆盖单独的方法;
*/
//接口-目标
interface Target {
void method1();
void method2();
}
//源类
abstract class Adapter implements Target {
public void method1() {
System.out.println("method 1");
}
public void method2() {
System.out.println("method 2");
}
}
public class InterfaceAdapter {
public static void main(String[] args) {
//new匿名抽象内部类覆盖单独的方法;
Target target = new Adapter() {
@Override
public void method2() {
System.out.println("method 3");
}
};
target.method1();
target.method2();
}
}