适配器设计模式一般有三种类型:类的适配器模式、对象的适配器模式、接口的适配器模式。
(1)类的适配器模式
public interface Targetable {
/* 与原类中的方法相同 */
public void method1();
/* 新类的方法 */
public void method2();
}
public class Source {
public void method1() {
System.out.println("this is original method!");
}
}
public class Adapter extends Source implements Targetable {
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
}
public class AdapterTest {
public static void main(String[] args) {
Targetable target = new Adapter();
target.method1();
target.method2();
}
}
输出结果:
this is original method!
this is the targetable method!
类图:
在类的适配器模式中,我们利用继承(Inheritance),构造了一个被适配者(Source类)的子类,再利用多态性(Polymorphism),让子类重写目标接口(Targetable)中我们需要的方法,这样就可以在不改变原有类(Source类)代码的基础上,实现目标接口要求的方法。
(2)对象的适配器模式
public class Source{
public void method1() { };
}
public interface Targetable {
void method1();
void method2();
}
public class Adapter implements Targetable {
private Source source;
public Adapter(Source source){
super();
this.source = source;
}
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
@Override
public void method1() {
source.method1();
}
}
public class AdapterTest {
public static void main(String[] args) {
Source source = new Source();
Targetable target = new Adapter(source);
target.method1();
target.method2();
}
}
类图
在对象的适配器模式中,源类(Source类)缺少目标接口中的部分方法,我们想要一个类既可以调用源类中已有方法,又实现了目标接口。那么我们构造一个适配器(Adapter类)实现目标接口(Targetable),并且有一个源类的实例。利用多态性(Polymorphism),重写源类需要的方法,即利用源类实例调用其方法;实现接口方法。
(3)接口的适配器模式
public interface ISourceable {
public void method1();
public void method2();
public void method3();
}
public abstract class BaseAdapter implements ISourceable{
public void method1() {}
public void method2() {}
public void method3() {}
}
public class ListAdapter extends BaseAdapter {
// 不用全部实现方法,只需要实现需要的就可以了
public void method3(){
System.out.println("the method3!");
}
}
类图:
在接口的适配器模式中,目标接口(ISourceable类)所要求的方法很多,但很多时候实现该接口的类(ListAdapter)并不需要所有的方法。我们可以创建一个抽象类(BaseAdapter类),实现所有方法。之后当我们写其他类需要实现该接口的时候,利用继承(Inheritance),继承抽象类,即可只重写我们需要的方法。