意图
将一个类的接口转换成另外一个客户希望的接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。
1. 类的适配器模式
有一个Source类,拥有一个方法,待适配,目标接口时Targetable,通过Adapter类,将Source的功能扩展到Targetable里.
public class Source {
public void method1(){
System.out.println("this is original method!");
}
}
public interface Targetable {
//和原类方法相同
public void method1();
//新的
public void method2();
}
public class Adapter extends Source implements Targetable{
@Override
public void method2() {
System.out.println("this is targetable method!");
}
}
2. 对象的适配器模式
基本思路和类的适配器模式相同,只是将Adapter类作修改,这次不继承Source类,而是持有Source类的实例,以达到解决兼容性的问题。
public class Wrapper implements Targetable{
private Source source;
public Wrapper(Source source){
super();
this.source = source;
}
@Override
public void method1() {
source.method1();
}
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
}
3. 接口的适配器模式
当不希望实现一个接口中所有的方法时,可以创建一个抽象类Wrapper,实现所有方法,我们写别的类的时候,继承抽象类即可。
public abstract class Wrapper2 implements Targetable{
@Override
public void method1() { }
@Override
public void method2() { }
}
public class SourceSub extends Wrapper2{
@Override
public void method1() {
System.out.println("this is first method!");
}
}
转自:http://blog.csdn.net/zhangerqing/article/details/8239539